c++11中的智能指针源于boost,所以也将 类enable_shared_from_this 和 及其成员函数shared_from_this()也给收编了。
通过模板方式继承enable_shared_from_this<T> 然后调用shared_from_this()函数返回对象T的shared_ptr指针,非常方便。使用时需要引用头文件 :#include <memory>
用例:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <memory>
using namespace std;
class TestA : public enable_shared_from_this<TestA>
{
public:
TestA()
{
cout << "TestA create" << endl;
}
~TestA()
{
cout << "TesA destory" << endl;
}
shared_ptr<TestA> getSharedFromThis() { return shared_from_this(); }
};
int main(){
{//出了此作用域 ptr1 ptr2 销毁, TestA对象销毁
shared_ptr<TestA> ptr1(new TestA());
shared_ptr<TestA> ptr2 = ptr1->getSharedFromThis();
cout << "ptr1 count: " << ptr1.use_count() << " ptr2 count: " << ptr2.use_count(