Re: Additional Glib::RefPtr Safety Mechanism





On Thu, 29 Aug 2019 at 21:27, Karsten Pedersen <kpedersen gmx com> wrote:
Hi all,

One area of C++ that always frustrates me is safety. Smart pointers
such as the Glib::RefPtr go a good way to avoid dangling pointers, use
after free, etc. However one area where this (and std::shared_ptr) is
lacking is that it is very easy for "this" to dangle and there really
is no protection against it. Check out a very simple example here:

https://github.com/osen/sr1/blob/master/src/tests/dangling_this.cpp


Is this actually a common problem that needs to be solved? 

It seems like a solution in search of a problem. IMO you should just avoid using globals like this when possible, and use them carefully when necessary.

For the shared_ptr example, you can solve the problem simply by copying the global into a local variable in the one function that needs to do it. That way you don't pay the cost in every function that uses operator->

  void broken()
  {
    auto keepalive = d;
    d = std::sr1::shared_ptr<Dummy>();
    dummy = 9;
  }
 
That keeps *this alive until the end of the function.

Or slightly more efficiently:

  void broken()
  {
    auto keepalive = std::move(d);
    d = std::sr1::shared_ptr<Dummy>();
    dummy = 9;
  }





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]