0

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.

Community
  • 1
  • 1
Carsten Greiner
  • 2,928
  • 2
  • 16
  • 20
  • Can you trim your question down to ... your actual question? It's good that you learned something today, but that's not pertinent to the question. – Kerrek SB Nov 17 '11 at 22:12
  • I think due to the lack of experience with shared_ptr, each answered question uncovers the next. K-Ballo's answer confirms that (1) is actually ok. Andy T's answer immediately answers the question that than popped up in my mind (where would I need enable_shared_from_this). – Carsten Greiner Nov 18 '11 at 07:58

2 Answers2

3

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 
Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112
  • +1 2nd sentence is about as clear as you can get it explained: `You want to share [...] by copying shared_ptr, but [...] implementation doesn't have any to make a copy from`. – sehe Nov 17 '11 at 22:40
  • Ah, now I understand the real need of the enable_shared_from_this. Thx. – Carsten Greiner Nov 18 '11 at 07:56
1

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.

K-ballo
  • 80,396
  • 20
  • 159
  • 169