Re: Additional Glib::RefPtr Safety Mechanism
Jonathan Wakely via gtkmm-list <[email protected]>
| Newsgroups | gmane.comp.gnome.gtkmm |
|---|---|
| Message-ID | <CAJcCCPNF5g5Z5-_Zaaf_0hSk_v5EBgF0rvbQ8WwCnFd-_rwbEQ@mail.gmail.com> |
On Thu, 29 Aug 2019 at 21:27, Karsten Pedersen <[email protected]> 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; } _______________________________________________ gtkmm-list mailing list [email protected] https://mail.gnome.org/mailman/listinfo/gtkmm-list