Thực tế bạn đang làm sai. Nếu bạn có thừa kế đơn giản, chỉ cần kế thừa từ enable_shared_from this
trong lớp cơ sở, và lớp dẫn xuất có được nó miễn phí. (Tất nhiên bạn sẽ cần phải downCast kết quả)
Nếu bạn có nhiều thừa kế (như có vẻ như), bạn phải sử dụng thủ thuật được mô tả here và cũng 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());
}
};
Sau đó, mã của bạn trở thành:
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>();
}
};
tôi không nghĩ rằng 'foo2' hoặc 'foo3' sẽ biên dịch ... – aschepler
vâng đó không có ý nghĩa, chỉ có hạng A được thừa hưởng enable_shared_from_this <> –
tôi nghĩ bạn nên có một cái nhìn vào những gì enable_shared_from_this làm. Xem câu trả lời cho [câu hỏi này] (http://stackoverflow.com/questions/712279/what-is-the-usefulness-of-enable-shared-from-this) –