In a C++ project that uses smart pointers, such as boost::shared_ptr
, what is a good design philosophy regarding use of "this
"?
Consider that:
It's dangerous to store the raw pointer contained in any smart pointer for later use. You've given up control of object deletion and trust the smart pointer to do it at the right time.
Non-static class members intrinsically use a
this
pointer. It's a raw pointer and that can't be changed.
If I ever store this
in another variable or pass it to another function which could potentially store it for later or bind it in a callback, I'm creating bugs that are introduced when anyone decides to make a shared pointer to my class.
Given that, when is it ever appropriate for me to explicitly use a this
pointer? Are there design paradigms that can prevent bugs related to this?
One example of correct use is
return *this;
in functions like operator++() and operator<<().When you are using a smart pointer class, you are right that is dangerous to directly expose "
this
". There are some pointer classes related toboost::shared_ptr<T>
that may be of use:boost::enable_shared_from_this<T>
boost::weak_ptr<T>
NULL
instead of a pointer to invalid memory. You can use weak pointers to get shared pointers to a valid reference-counted object.Neither of these is foolproof, of course, but they'll at least make your code more stable and secure while providing appropriate access and reference counting for your objects.