如果一个类的对象被shared_ptr管理着,然后该类的某个成员函数需要返回一个指向该对象本身的shared_ptr,该怎么实现呢?
- #include
- #include
- using namespace std;
-
- class A
- {
- public:
- shared_ptr getSharedPtr()
- {
- }
-
- ~A()
- {
- cout << "Destruct A" <
- }
- };
-
- int main()
- {
- shared_ptr sp1(new A());
- shared_ptr sp2 = sp1->getSharedPtr();
-
- cout << "sp1.use_count() = " << sp1.use_count() << endl;
- cout << "sp2.use_count() = " << sp2.use_count() << endl;
- return 0;
- }
运行程序输出:
sp1.use_count() = 1
sp2.use_count() = 1
Destruct A
Destruct A
异常退出
可见通过shared_ptr(this)这种方式虽然返回了一个shared_ptr对象,但是这里有一个问题。就是sp1和sp2成为了没有任何关联的两个智能指针对象。
通过以下文章
可以了解到,智能指针是通过一个管理对象管理着对象的计数,当多个智能指针引用到同一个对象时,是通过其管理对象来进行维护的。
但是shared_ptr(this)这种方式相当于通过this重新构造了一个shared_ptr,也就是说也重新生成了一个管理对象。
因此sp1和sp2虽然都引用到了一个对象上,但是其之间没有任何关联(sp1和sp2分别有自己的管理对象)。
由此才导致程序的运行输出为,sp1和sp2的引用计数分别为1,并且调用了两次A的析构函数。
为了解决这种问题,可以使用C++11新增的enable_shared_from_this作为基类,该类提供了成员函数shared_from_this可以返回一个指向当前对象的shared_ptr:
- #include
- #include
- using namespace std;
-
- {
- public:
- shared_ptr getSharedPtr()
- {
- return shared_from_this();
- }
-
- ~A()
- {
- cout << "Destruct A" <
- }
- };
-
- int main()
- {
- shared_ptr sp1(new A());
- shared_ptr sp2 = sp1->getSharedPtr();
-
- cout << "sp1.use_count() = " << sp1.use_count() << endl;
- cout << "sp2.use_count() = " << sp2.use_count() << endl;
- return 0;
- }
运行程序输出:
sp1.use_count() = 2
sp2.use_count() = 2
Destruct A
符合预期,sp1和sp2共享了对象,析构函数也只被调用了一次。
-
相关阅读:
安卓APP全局黑白化实现方案
苹果电脑如何优化MAC系统内存?怎么清理系统垃圾?
正则表达式(Linux 下搭配 grep 使用)
在 Excel 中使用 Python 自动填充公式
gcc -c/-o的作用
【 Git 】 Merge or Rebase
从计网的角度讲明白什么是网关
JAVASE语法零基础——抽象类和接口
没域名也可以frp实现内网穿透 SSH,个人搭建内网穿透 7月6日
C语言函数strcmp比较字符串使用方法,scanf中空格输入小结。
-
原文地址:https://blog.csdn.net/jiemashizhen/article/details/126276295