将enable_shared_from_this与多个继承一起使用 [英] Use of enable_shared_from_this with multiple inheritance
问题描述
BI正在我的代码中使用enable_shared_from_this
,但我不确定其用法是否正确.这是代码:
BI am using enable_shared_from_this
in my code, and I am not sure if its usage is correct. This is the code:
class A: public std::enable_shared_from_this<A>
{
public:
void foo1()
{
auto ptr = shared_from_this();
}
};
class B:public std::enable_shared_from_this<B>
{
public:
void foo2()
{
auto ptr = shared_from_this();
}
};
class C:public std::enable_shared_from_this<C>
{
public:
void foo3()
{
auto ptr = shared_from_this();
}
};
class D: public A, public B, public C
{
public:
void foo()
{
auto ptr = A::shared_from_this();
}
};
假设总是通过D的shared_ptr
调用make_shared_from_this()
的这些用法正确吗?
Are these usage of make_shared_from_this()
correct, assuming that they are always being called through shared_ptr
of D?
推荐答案
确实是您做错了.如果您具有简单的继承,则只需从基类中的enable_shared_from this
继承,派生类即可免费获得它. (当然,您需要向下转换结果)
Indeed you are doing it wrong. If you have simple inheritance, just inherit from enable_shared_from this
in the base class, and derived class get it for free. (of course you'll need to downcast the result)
如果您有多个继承(看起来像),则必须使用此处:
If you have multiple inheritance (like it seems), you must use the trick described here and also here :
/* Trick to allow multiple inheritance of objects
* inheriting shared_from_this.
* cf. https://stackoverflow.com/a/12793989/587407
*/
/* First a common base class
* of course, one should always virtually inherit from it.
*/
class MultipleInheritableEnableSharedFromThis: public std::enable_shared_from_this<MultipleInheritableEnableSharedFromThis>
{
public:
virtual ~MultipleInheritableEnableSharedFromThis()
{}
};
template <class T>
class inheritable_enable_shared_from_this : virtual public MultipleInheritableEnableSharedFromThis
{
public:
std::shared_ptr<T> shared_from_this() {
return std::dynamic_pointer_cast<T>(MultipleInheritableEnableSharedFromThis::shared_from_this());
}
/* Utility method to easily downcast.
* Useful when a child doesn't inherit directly from enable_shared_from_this
* but wants to use the feature.
*/
template <class Down>
std::shared_ptr<Down> downcasted_shared_from_this() {
return std::dynamic_pointer_cast<Down>(MultipleInheritableEnableSharedFromThis::shared_from_this());
}
};
然后您的代码变为:
class A: public inheritable_enable_shared_from_this<A>
{
public:
void foo1()
{
auto ptr = shared_from_this();
}
};
class B: public inheritable_enable_shared_from_this<B>
{
public:
void foo2()
{
auto ptr = shared_from_this();
}
};
class C: public inheritable_enable_shared_from_this<C>
{
public:
void foo3()
{
auto ptr = shared_from_this();
}
};
class D: public A, public B, public C
{
public:
void foo()
{
auto ptr = A::downcasted_shared_from_this<D>();
}
};
这篇关于将enable_shared_from_this与多个继承一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!