因此,为了防止这个问题,你可以让你的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
}
如果你发现自己希望为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();
你到底在问什么?你想知道是否有办法防止在堆栈分配的对象上调用'shared_from_this()'? – 2010-08-26 10:08:53