首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::enable_shared_from_this::shared_from_this

shared_ptr<T> shared_from_this();

(1)

shared_ptr<T const> shared_from_this() const;

(2)

返回std::shared_ptr<T>拥有*this所有的std::shared_ptr指的是*this...

有效执行std::shared_ptr<T>(weak_this),在哪里weak_this私人可变std::weak_ptr<T>成员enable_shared_from_this...

注记

它被允许打电话shared_from_this仅在以前共享的对象上,即在std::shared_ptr。否则,在C++17%29之前,该行为是未定义的%28。std::bad_weak_ptr由共享引发%28。[医]来自默认构造的PTR构造函数weak_this%29%28自C++17%29。

返回值

std::shared_ptr<T>拥有*this先存std::shared_ptrS.

二次

代码语言:javascript
复制
#include <iostream>
#include <memory>
 
struct Foo : public std::enable_shared_from_this<Foo> {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; } 
    std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};
 
int main() {
    Foo *f = new Foo;
    std::shared_ptr<Foo> pf1;
 
    {
        std::shared_ptr<Foo> pf2(f);
        pf1 = pf2->getFoo();  // shares ownership of object with pf2
    }
 
    std::cout << "pf2 is gone\n";   
}

二次

产出:

二次

代码语言:javascript
复制
Foo::Foo
pf2 is gone
Foo::~Foo

二次

另见

shared_ptr (C++11)

smart pointer with shared object ownership semantics (class template)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券