1. 程式人生 > 其它 >C++11 std::enable_shared_from_this

C++11 std::enable_shared_from_this

官網描述

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 provides the type T with a member function shared_from_this. If an object t of type T is managed by a std::shared_ptr named pt, then calling T::shared_from_this will return a new std::shared_ptr that shares ownership of t with pt.

知乎

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;
}