保活 std::enable_shared_from_this<Good>
#include <memory>
#include <iostream>
struct Good : std::enable_shared_from_this<Good> // 注意:继承
{
public:
std::shared_ptr<Good> getptr() {
return shared_from_this();
}
~Good() { std::cout << "Good::~Good() called" << std::endl; }
};
int main()
{
// 大括号用于限制作用域,这样智能指针就能在system("pause")之前析构
{
std::shared_ptr<Good> gp1(new Good());
std::shared_ptr<Good> gp2 = gp1->getptr();
// 打印gp1和gp2的引用计数
std::cout << "gp1.use_count() = " << gp1.use_count() << std::endl;
std::cout << "gp2.use_count() = " << gp2.use_count() << std::endl;
}
}
g++ -g -Wall -std=c++11 -pthread baohu.cpp -o baohu
[root@localhost test]# ./baohu
gp1.use_count() = 2
gp2.use_count() = 2
Good::~Good() called
【转】:https://blog.csdn.net/caoshangpa/article/details/79392878
浙公网安备 33010602011771号