std::enable_shared_from_this<T>::shared_from_this
來自 cppreference.com
< cpp | 記憶體 | enable shared from this
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(); // shares ownership of object with pf2 } std::cout << "pf2 is gone\n"; }
輸出
Foo::Foo pf2 is gone Foo::~Foo
[編輯] 參閱
(C++11) |
具有共享物件所有權語義的智慧指標 (類模板) |