C++11 std::enable_shared_from_this
阿新 • • 發佈:2022-04-02
官網描述
std::enable_shared_from_this allows an object t that is currently managed by a std::shared_ptr named pt to safely generate additional std::shared_ptr instances pt1, pt2, ... that all share ownership of t with pt.
Publicly inheriting from std::enable_shared_from_this
知乎
std::enable_shared_from_this 有什麼意義? - 尤不二的回答 - 知乎
https://www.zhihu.com/question/30957800/answer/50181754
code
#include<cstdio> #include<memory> #include<cstring> #include<string> #include<iostream> class Test: public std::enable_shared_from_this<Test> { public: Test() = default; //enable_shared_from_this允許在函式內部獲取指向該物件的shared_ptr指標 std::shared_ptr<Test> getPtr() { return shared_from_this(); } int getValue() const { return value; } private: const static int value = 10; }; int main() { Test* a = new Test(); std::shared_ptr<Test> ptr(a); std::cout << a->getPtr()->getValue(); return 0; }