[PtrContainer] Inserting "this" Pointers

Dear all, Is inserting "this" pointers into pointer containers valid? If so, what are the consequences? Would that need special care for example? TIA, --Hossein

I am not an expert on "this", so my understanding below may not be accurate.
The insertion itself is of course valid:
class A
{
...
void insert_me(std::vector& v) { v.push_back(this); }
};
However, consider how the client may use it:
A* aa = ...;
aa->insert_me(v);
Since you get a hand on aa already, why don't you just call instead:
v.push_back(aa);
Now if you use smart pointers instead of naked pointers, the latter approach
lets the client code handle it, which will be easy with for example
shared_ptr. There is no insert_me(), and therefore not a chance for
insert_me() to impose extra (and probably confusing) assumption about how
multiple smart pointers should manage the life cycle.
If you insist using insert_me() with smart pointers, as as Benjamin pointed
out, you may need to use boost::enable_shared_from_this. Otherwise a
shared_ptr instantiated with a this pointer in insert_me() is very
dangerous, because it will eventually try to delete aa even if aa was
created on the stack.
--------------------------------------------------
From: "Hossein Haeri"
Dear all,
Is inserting "this" pointers into pointer containers valid? If so, what are the consequences? Would that need special care for example?
TIA, --Hossein
_______________________________________________ Boost-users mailing list Boost-users@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users

Hi Binglong,
Since you get a hand on aa already, why don't you just call instead: v.push_back(aa);
Because my insert_to() isn't just a simple push_back(); It requires non-trivial computations beforehand.
If you insist using insert_me() with smart pointers, as as Benjamin pointed out, you may need to use boost::enable_shared_from_this. Otherwise a shared_ptr instantiated with a this pointer in insert_me() is very dangerous, because it will eventually try to delete aa even if aa was created on the stack.
Yes, I can well remember this nice discussion on our other thread. My motivation for targeting pointer containers instead of STL ones in combination with smart pointers is to get rid of the messy and error-prone pointer arithmetic. (I'm still reading the documentation.) I don't still know how pointer containers internally manage the dynamically allocated pieces of memory. Thus, I'm exploring the matter and am specifically interested in knowing whether I would need to use enable_shared_from_this and make_shared for container pointers too? And, if yes, how would I need to do that if I'm about to store "this" pointers inside them? TIA, --Hossein
participants (2)
-
Binglong Xie
-
Hossein Haeri