
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