小编Hen*_*ang的帖子

这个shared_ptr如何自动转换为原始指针?

我现在正在学习enable_shared_from_thisC++ 11; 一个例子让我感到困惑:shared_ptr返回的类型如何shared_from_this()转换为这个原始指针?

#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); …
Run Code Online (Sandbox Code Playgroud)

c++ c++-standard-library c++11

4
推荐指数
1
解决办法
144
查看次数

标签 统计

c++ ×1

c++-standard-library ×1

c++11 ×1