mardi 8 mai 2018

Why do we use enable_shared_from_this template?

Recently I have met the std::enable_shared_from_this<T> template, which is the same as its Boost version.
So It describes the following sample code:

class Y: public enable_shared_from_this<Y>
{
public:

    shared_ptr<Y> f()
    {
        return shared_from_this();
    }
}

int main()
{
    shared_ptr<Y> p(new Y);
    shared_ptr<Y> q = p->f();
    assert(p == q);
    assert(!(p < q || q < p)); // p and q must share ownership
}

What is the reason creating the shared_ptr through f()?
Whats wrong with shared_ptr<Y> p(new Y);?

Aucun commentaire:

Enregistrer un commentaire