如何解决将此指针转换为boost :: shared_ptr?
| 我有一个基类,我想将其指针转换为其派生类shared_ptr。在我的情况下,我不能使用继承enable_shared_from_this。那么还有其他有效的方法吗? 例如typedef boost::shared_ptr <a> aPtr;
typedef boost::shared_ptr <b> bPtr;
Class a{
void fun();
}
class b : public a{
}
a::fun(){
//how to carry out this conversion below
bPtr bpointer = dynamic_cast<bPtr>(this);
}
解决方法
您需要
boost::enable_shared_from_this
。请参阅文档:
class Y: public boost::enable_shared_from_this<Y>
{
public:
boost::shared_ptr<Y> f()
{
return shared_from_this();
}
}
int main()
{
boost::shared_ptr<Y> p(new Y);
boost::shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p)); // p and q must share ownership
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。