用enable_shared_from_this在类的成员函数中获得指向当向前对象的shared_ptr
来源:互联网 发布:假面骑士555知乎 编辑:程序博客网 时间:2024/04/29 10:35
下面的代码编译没有问题,运行时错误。错误发生在voidtest1()销毁ptr时,认为ptr是最后一个指向A对象的shared_ptr,于是它试图销毁此对象。按理说main函数中有一个shared_ptr指向A的对象,那么test1()因该不会销毁ptr指向的对象。单步跟踪后,发现test1()::ptr的use_count_等于1(我认为因该是2)。
使用enable_shared_from_this
单步跟踪发现A::test1()调用shared_from_this()后A::test1()::ptr的use_count_等于2,所以test1()::ptr不会销毁它指向的对象。
- // class A
- #include <boost/shared_ptr.hpp>
- #include "B.h"
- using namespace boost;
- class B;
- class A
- {
- public:
- A()
- {
- mB = NULL;
- mI = 1;
- }
- ~A()
- {
- if( NULL!=mB )
- {
- delete mB;
- }
- }
- void test1()
- {
- shared_ptr <A> ptr(this);
- B b(ptr);
- b.print();
- }
- };
- //class B
- #include <boost/shared_ptr.hpp>
- #include <iostream>
- using namespace boost;
- using namespace std;
- class A;
- class B
- {
- public:
- B(shared_ptr <A> a)
- {
- A* a_ptr=a.get();
- mAshptr = a;
- }
- B(A* a)
- {
- mAptr = a;
- }
- B(A& a){mAptr=&a;}
- ~B()
- {
- }
- void print()
- {
- cout < <"BB" < <endl;
- }
- private:
- shared_ptr <A> mAshptr;
- A* mAptr;
- };
- //main.cpp
- #include "A.h"
- int main()
- {
- shared_ptr <A> ptr(new A());
- ptr->test1();
- }
- #include <boost/shared_ptr.hpp>
- #include <boost/enable_shared_from_this.hpp>
- #include "B.h"
- using namespace boost;
- class B;
- class A : public enable_shared_from_this <A>
- {
- public:
- A()
- {
- mB = NULL;
- mI = 1;
- }
- ~A()
- {
- if( NULL!=mB )
- {
- delete mB;
- }
- }
- void test1()
- {
- shared_ptr <A> ptr = shared_from_this();
- B b(ptr);
- b.print();
- }
- };
- 用enable_shared_from_this在类的成员函数中获得指向当向前对象的shared_ptr
- 当指针并没有指向实际的对象时,能否调用对象的成员函数
- 第五周 阅读程序 在 main 函数中,可设置指向对象public 成员、对象函数还有对象的指针
- 指向对象的指针访问成员函数
- C++:指向对象成员函数的指针
- c++指向对象成员函数的指针
- C++中 指向成员函数的指针
- C++里,在类中使用指向类成员函数的指针
- 对enable_shared_from_this、weak_ptr、shared_ptr的理解
- 指向 类成员函数 的 函数指针
- 用对象和用指向基类的指针访问成员函数
- 指向类的成员函数的指针
- 指向对象成员的指针
- 指向对象成员的指针
- C++指向类成员函数的指针
- C++指向类成员函数的指针
- C++指向类成员函数的指针
- C++指向类成员函数的指针
- [C#.NET]制作包含自定义操作的安装包
- DBUS问题
- 男人三十 真正的考验才刚刚开始
- 针对HP-UNIX的telnet java程序 - Java - JavaEye知识库
- 大型网站架构演变和知识体系
- 用enable_shared_from_this在类的成员函数中获得指向当向前对象的shared_ptr
- “/NeuJob”应用程序中的服务器错误。
- 在JDK1.4中使用replace(CharSequence target, CharSequence replacement)
- 等待
- 什么是多态?为什么用多态?有什么好处?[转]
- 林蛙简介
- 黑鹰ASP.NET教程
- 第一讲:Java程序的编写和运行
- 第五日