一、简介
shared_from_this() 是 C++11 标准引入的功能,它定义在<shared_ptr.h>文件内,用于从一个继承自 enable_shared_from_this 的类中获取一个指向当前对象的shared_ptr指针。
二、使用
1. shared_from_this()的使用场景:
当一个类使用shared_ptr进行了托管,而这个类的成员函数想把类对象作为参数传给其他函数时
,就需要使用shared_from_this()获取一个指向自身的share_ptr。
2. 使用示例:
#include <iostream>
#include <memory>
#include <functional>
using namespace std;
class Test;
/**
* 一个参数为shared_ptr<Test>的普通函数
*/
void func(const shared_ptr<Test> &test){
cout << "execute callback ...." << endl;
};
class Test
: public enable_shared_from_this<Test>
{
public:
Test()
: _data(new char[1])
{
cout << "Test()" << endl;
};
~Test() {
cout << "~Test()" << endl;
delete[] _data;
}
/**
* 一个把类对象作为参数传递的成员函数
*/
void test() {
/* func(this); // 编译不通过 */
/* func(shared_ptr<Test>(this)); // 造成析构函数调用两次 */
func(shared_from_this());
}
private:
char *_data;
};
int main() {
shared_ptr<Test> t1(new Test());
t1->test();
return 0;
}
三、注意事项
1. 不能在成员函数里将this裸指针直接传出去,编译通不过
,(因为把一个裸指针传递给调用者,谁也不知道调用者会做什么操作,假如调用者delete了该对象,而原来的shared_ptr此时还指向者该对象)。
2. 使用shared_ptr将this包装后传出去也会有问题,析构函数会被调用两次
,因为当裸指针同时赋值给多个shared_ptr后,这些shared_ptr不是共享所有权的,在离开时作用域时会分别调用裸指针的析构函数。
示例:
void test1() {
shared_ptr<Test> t1(new Test());
/* t1->test(); */
cout << "此时的引用计数为:" << t1.use_count() << endl;
shared_ptr<Test> t2 = t1; // 共享所有权
cout << "此时的引用计数为:" << t1.use_count() << endl;
shared_ptr<Test> t3(t1); // 共享所有权
cout << "此时的引用计数为:" << t1.use_count() << endl;
shared_ptr<Test> t4(t1.get()); // <---------- 直接管理裸指针,非共享所有权
cout << "此时的引用计数为:" << t1.use_count() << endl;
}