cyb*_*vnm 10 c++ boost smart-pointers
如何为堆栈分配的对象调用shared_from_this?在基类列表中的enable_shared_from_this是派生类的用户的指示器,用于仅在堆上创建它(我们只是希望正确的类使用)或者我们可以对这些错误有更强的保护吗?或者我不明白一些时刻?
示例代码:
__CODE__返回COUNT个查询?
那么.. foo的精确运行时类型是什么?
class C : public enable_shared_from_this<C>
{
public:
shared_ptr<C> method() { shared_from_this(); }
};
void func()
{
C c;
shared_ptr<C> ptr = c.method(); // exception comming from shared_from_this()
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*son 12
因此,为了防止这个问题你可以使你的contstructors私有,只提供返回shared_ptr的创建函数 - 这样就不能在堆栈上分配对象,如下所示:
class C : public enable_shared_from_this<C>
{
public:
static shared_ptr<C> create() { return shared_ptr<C>(new C() ); }
shared_ptr<C> method() { shared_from_this(); }
private:
C() {...}
// Make operator= and C(const C&) private unimplemented
// so the used cant do bad things like C c( * c_ptr );
C& operator=( const C & );
C( const C & );
};
void func()
{
C c; // This doesnt compile
shared_ptr<C> ptr = c.method(); // So you can never get this
}
void altfunc()
{
shared_ptr<C> c_ptr = C::create();
C & c_ref = *c;
shared_ptr<C> ptr = c_ref.method(); // OK
}
Run Code Online (Sandbox Code Playgroud)
如果您发现自己希望使用anoperator =您可以使用私有实现的复制构造函数提供克隆函数,就像这样
// This goes in class C
shared_ptr<C> C::clone() const
{
return shared_ptr<C>( new C(*this) );
}
// This is how you can use it
shared_ptr<C> c2 = c1->clone();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2585 次 |
| 最近记录: |