双重继承enable_shared_from_this [英] Double inheritance of enable_shared_from_this
问题描述
我有一个来自其他两个对象(A和B)的对象(Z)。
A和B都派生自 enable_shared_from_this< ;>
,分别 enable_shared_from_this< A>
和 enable_shared_from_this< B>
p>
当然我调用 shared_from_this()
在Z.当然编译器报告这是不明确的。
我的问题是:
- 可以安全地从
- 如果不安全,我该如何解决这个问题?
注意:
我找到了另一个问题坏的弱指针,当基类和派生类都继承自boost :: enable_shared_from_this 但它没有真正回答。我应该使用 virtual
把戏吗?
基本和派生类都继承自boost :: enable_shared_from_this 的解决方案是使用虚拟继承。这里是C ++ 11标准的实现 shared_ptr
(不是Boost):
#include< memory>
struct virtual_enable_shared_from_this_base:
std :: enable_shared_from_this< virtual_enable_shared_from_this_base> {
virtual〜virtual_enable_shared_from_this_base(){}
};
template< typename T>
struct virtual_enable_shared_from_this:
virtual virtual_enable_shared_from_this_base {
std :: shared_ptr< T> shared_from_this(){
return std :: dynamic_pointer_cast< T>(
virtual_enable_shared_from_this_base :: shared_from_this());
}
};
struct A:virtual_enable_shared_from_this< A> {};
struct B:virtual_enable_shared_from_this< B> {};
struct Z:A,B {};
int main(){
std :: shared_ptr< Z> z = std :: make_shared< Z>();
std :: shared_ptr< B> b = z-> B :: shared_from_this();
}
这不是默认实现的一部分,可能是因为虚拟继承。
I have an object (Z) which derives from two other objects (A and B).
A and B both derive from enable_shared_from_this<>
, respectively enable_shared_from_this<A>
and enable_shared_from_this<B>
.
Of course I call shared_from_this()
on Z. And of course the compiler reports this as ambiguous.
My questions are :
- is it safe to inherit twice from
enable_shared_from_this<>
or will it create two separated reference counts (bad !) - If not safe, how do I solve this ?
Note :
I've found this other question bad weak pointer when base and derived class both inherit from boost::enable_shared_from_this but it doesn't really answer. Should I use the virtual
trick too ?
Yes, as per bad weak pointer when base and derived class both inherit from boost::enable_shared_from_this the solution is to use virtual inheritance. Here's an implementation for the C++11 standard shared_ptr
(not Boost):
#include <memory>
struct virtual_enable_shared_from_this_base:
std::enable_shared_from_this<virtual_enable_shared_from_this_base> {
virtual ~virtual_enable_shared_from_this_base() {}
};
template<typename T>
struct virtual_enable_shared_from_this:
virtual virtual_enable_shared_from_this_base {
std::shared_ptr<T> shared_from_this() {
return std::dynamic_pointer_cast<T>(
virtual_enable_shared_from_this_base::shared_from_this());
}
};
struct A: virtual_enable_shared_from_this<A> {};
struct B: virtual_enable_shared_from_this<B> {};
struct Z: A, B { };
int main() {
std::shared_ptr<Z> z = std::make_shared<Z>();
std::shared_ptr<B> b = z->B::shared_from_this();
}
This isn't part of the default implementation, probably because of the overhead of virtual inheritance.
这篇关于双重继承enable_shared_from_this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!