Reputation: 2938
I am currently reading through C++ TR1 extensions and started focussing on std::tr1::shared_ptr.
So, I read so far that I can declare and initialize shared_ptr<> with this code:
class foo {};
std::tr1::shared_ptr<foo> fsp(new foo);
std::tr1::shared_ptr<foo> fps2(fsp); // (1) init using first sp
Now I read about enable_shared_from_this ( http://msdn.microsoft.com/en-us/library/bb982611%28v=VS.90%29.aspx ) and see this example:
class foo : public enable_shared_from_this<foo> {};
std::tr1::shared_ptr<foo> fsp(new foo);
std::tr1::shared_ptr<foo> fps2 = fsp->shared_from_this(); // (2) init using first sp
My question is, why would I want to use shared_from_this in comparison to the initalization I labeled as "(1) init using first sp".
I have read the article What is the usefulness of `enable_shared_from_this`? and now better understand the usefulness of it.
But that leaves me open whether my "(1) init using first sp" is ok or what downsides I could face using it.
Upvotes: 0
Views: 1707
Reputation: 16286
enable_shared_from_this
is most useful in class implementation whose objects will be shared. You want to share the same reference counter for all instances of shared_ptr
s of your object (is usually done by copying shared_ptr
), but class implementation doesn't have any to make a copy. In this case you can use shared_from_this
.
Consider:
struct A;
void f(shared_ptr<A> const&) {...}
struct A: public enable_shared_from_this<A>
{
void a_f()
{
// you need to call f() here passing itself as a parameter
f(shared_from_this());
}
};
shared_ptr<A> a_ptr(new A());
a_ptr->a_f(); // in inner call to f() will be used temporary shared_ptr<A>
// that uses (shares) the same reference counter as a_ptr
Upvotes: 3
Reputation: 81409
AFAIK your statement (1) is ok. enable_shared_from_this
is about getting a shared_ptr
from the object, if you do have the shared_ptr
already then you don't need to call it.
Upvotes: 1