Multiple Inheritance and enable_shared_from_this

本文详细探讨了 C++ 中 shared_from_this 的使用方法及其注意事项。包括如何确保多个 shared_ptr 实例共享引用计数,调用 shared_from_this 的前提条件,以及在多重继承中正确获取 derived 类型的 shared_ptr。

http://www.codeproject.com/Articles/286304/Solution-for-multiple-enable_shared_from_this-in-i

http://boost.2283326.n4.nabble.com/smart-ptr-enable-shared-from-this-and-multiple-inheritance-solution-td3058364.html

http://stackoverflow.com/questions/5232712/questions-regarding-shared-from-this

1)shared_from_this enables you to guarantee that if you have one shared_ptr instance to your object then you can construct another without copying the first, and that these instances will share the reference count. You could achieve this by storing a weak_ptr as a class member, and setting that value when you first allocate a shared_ptr to your object.

2) Calling shared_from_this() requires that there is at least one shared_ptr instance already pointing to your object. If you use it on an automatic object without a shared_ptr instance with a custom deleter then you will get bad stuff happening.

3) If you derive from your class then the enable_shared_from_this functionality will give you a shared_ptr to the base class (the one that derived from enable_shared_from_this). You could then use static_pointer_cast or dynamic_pointer_cast to cast the result of shared_from_this() to a pointer to the derived class.

转载于:https://www.cnblogs.com/androidme/archive/2013/02/03/2890856.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值