2010-08-26 67 views
6

对于堆栈分配的对象调用shared_from_this怎么样?在基类列表中的enable_shared_from_this是派生类用户的指示符,用于创建仅在堆上(我们只希望正确使用类的用法),或者我们可以对这些错误提供更强的保护?或者我不明白一些时刻?

示例代码: enable_shared_from_this和堆栈上的对象

 
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() }

+1

你到底在问什么?你想知道是否有办法防止在堆栈分配的对象上调用'shared_from_this()'? – 2010-08-26 10:08:53

回答

10

因此,为了防止这个问题,你可以让你的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(); 
+0

我知道,如果你愿意跳过一些箍来故意邪恶的话,你可能仍然可以在堆栈上分配这些内容。但恕我直言,这可以防止大多数无辜的错误。 – 2010-08-26 10:24:34

+0

所以我们最初将设计堆堆类......这种方法是否被广泛使用? – cybevnm 2010-08-26 12:45:08

+0

为什么你需要禁用赋值操作符?分配给shared_ptr中保存的对象通常很好。它的处理方式与两个*现有*对象之间的任何其他赋值相同 - 引用计数不会受到影响。这两个不同的*对象在赋值之后将具有相同的内容。 – nobar 2011-02-24 04:50:03