How should I avoid using the "this" pointer in conjunction with smart pointers? Are there any design patterns/general suggestions on working around this?
I'm assuming combining the two is a no-no since either:
- you're passing around a native pointer to a smart pointer-managed object which defeats the point of using the smart pointers in the first place,
- if you wrap the "this" pointer in a smart pointer at use, e.g. "return CSmartPtr(this);", you've effectively set up multiple smart pointers managing the same object so the first one to have a reference count of zero will destroy the object from under the other, or
- if you have a member variable holding the value of CSmartPtr(this) to return in these cases, it'll ultimately be a circular reference that results in the reference count always being one.
To give a bit of context, I recently learned about the negative implications of combining STL containers with objects (repeated shallow copying, slicing when using containers of a base class, etc), so I'm replacing some usage of these in my code with smart pointers to the objects. A few objects pass around references to themselves using the "this" pointer, which is where I'm stuck.
I've found smart pointers + “this” considered harmful? asked on a somewhat similar problem, but the answer isn't useful as I'm not using Boost.
Edit: A (very contrived) example of what I'd been doing would be
...::AddToProcessingList(vector<CSmartPtr> &vecPtrs)
{
vecPtrs.push_back(CSmartPtr(this));
}