Search code examples
c++tr1

c++ tr1 enable_shared_from_this what's the advantage?


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.


Solution

  • 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_ptrs 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