mardi 29 janvier 2019

How is this shared_ptr automatically converted to a raw pointer?

I'm studying enable_shared_from_this of C++11 now; one example made me confused: how the shared_ptr type returned by shared_from_this() can convert to this raw pointer?

#include <iostream>
#include <memory>
#include <functional>

struct Bar {
    Bar(int a) : a(a) {}
    int a;
};

struct Foo : public std::enable_shared_from_this<Foo> {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; }

    std::shared_ptr<Bar> getBar(int a)
    {
        std::shared_ptr<Bar> pb(
            new Bar{a}, std::bind(&Foo::showInfo, shared_from_this(), std::placeholders::_1)
        );
        return pb;
    }

    void showInfo(Bar *pb)
    {
        std::cout << "Foo::showInfo()\n";
        delete pb;
    }

};

int main()
{
    std::shared_ptr<Foo> pf(new Foo);
    std::shared_ptr<Bar> pb = pf->getBar(10);
    std::cout << "pf use_count: " << pf.use_count() << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire