【发布时间】:2016-03-06 16:26:52
【问题描述】:
我发现的enable_shared_from_this 示例显示它是通过继承使用的。例如:
struct Good : enable_shared_from_this<Good> {
shared_ptr<Good> getptr() {
return shared_from_this();
}
};
int main() {
// Good: the two shared_ptr's share the same object
shared_ptr<Good> gp1(new Good);
shared_ptr<Good> gp2 = gp1->getptr();
cout << "gp2.use_count() = " << gp2.use_count() << endl;
}
在我这一天,我被警告过很多关于从标准库继承的危险。这段代码当然似乎也有这些危险,例如:
struct A : enable_shared_from_this<A> {};
struct B : enable_shared_from_this<B> {};
如果我想创建struct C : A, B {};,关键点显然是C::shared_from_this()。显然我们可以解决这个问题,但存在一些固有的复杂性。
所以我的问题是,有没有办法将 enable_shard_from_this 用作 has-a 关系而不是 is-a 关系?
【问题讨论】:
-
关于第3点:没有
enable_shared_from_this;有enable_shared_from_this<D>。这个很重要。如果A派生自enable_shared_from_this<A>和B派生自enable_shared_from_this<B>,那么它们是不同的基类。 -
这在实践中并不是一个常见的问题。如果这是一个问题,则表明复杂性已经存在:您过度使用
enable_shared_from_this或者您的类层次结构应该更改为具有提供shared_from_this功能的单个基类。 -
1.析构函数是受保护的,所以它不是虚拟的也没关系。无论如何,没有人可以直接调用它。 2.析构函数不会破坏
*this。这不可以。 3.如果你看到一个症结,请指出它的确切位置。 -
另见this。来自 enable_shared_from_this 的无限制多重继承不起作用,但随后将 shared_ptr 与无限制 MI 一起使用也不起作用,因此不会丢失任何价值。
-
回复:“我在这一天被警告过很多关于从标准库继承的危险”,这太宽泛了。您应该被警告不要从非设计派生的事物中派生。
enable_shared_from_this是旨在派生自,对继承的一般恐惧不应成为决定是否以设计使用方式使用它的因素。
标签: c++ inheritance destructor shared-ptr member