Namespaces
Variants

std::enable_shared_from_this<T>:: shared_from_this

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
std:: shared_ptr < T > shared_from_this ( ) ;
(1) (自 C++11 起)
std:: shared_ptr < T const > shared_from_this ( ) const ;
(2) (自 C++11 起)

返回一个 std:: shared_ptr < T > ,该指针与所有指向 * this 的现有 std:: shared_ptr 共享 * this 的所有权。

目录

返回值

std:: shared_ptr < T > ( weak_this  )

异常

如果在未被 std::shared_ptr 共享的对象上调用 shared_from_this std::shared_ptr 构造函数将抛出 std::bad_weak_ptr 异常。

示例

#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(); // 与 pf2 共享对象所有权
    }
    std::cout << "pf2 is gone\n";   
}

输出:

Foo::Foo
pf2 is gone
Foo::~Foo

参见

(C++11)
具有共享对象所有权语义的智能指针
(类模板)