从第三方定义的类继承时shared_from_this
shared_from_this when inheriting from class defined by third party
我在尝试研究我的问题时阅读了许多关于堆栈溢出的文章,内容涉及shared_from_this、bad_weak_ptr异常和多重继承。他们都建议你从enable_shared_from_this继承一个基类,然后从中派生。那么,当您必须派生的类来自您无法编辑的第三方库时,该怎么办?
例:
#include <iostream>
#include <memory>
class ThirdPartyClass
{
public:
ThirdPartyClass() {}
ThirdPartyClass(const ThirdPartyClass &) = delete;
virtual ~ThirdPartyClass() {};
};
class A : public ThirdPartyClass, std::enable_shared_from_this<A>
{
public:
A():ThirdPartyClass(){}
virtual ~A(){}
void Foo();
};
void DoStuff(std::shared_ptr<A> ptr)
{
std::cout << "Good job if you made it this far!" << std::endl;
}
void A::Foo()
{
DoStuff(shared_from_this()); // throws here
}
int main() {
std::shared_ptr<A> a = std::make_shared<A>();
a->Foo();
return 0;
}
您收到错误是因为您不是从enable_shared_from_this
和shared_ptr
的公共继承,并且make_shared
无法检测到对象需要此类支持。不是因为从第三方类继承。
因此,要修复仅作为公共继承:
class A : public ThirdPartyClass, public std::enable_shared_from_this<A>
相关文章:
- 如何解决"invalid conversion from 'char' to 'const char*'"
- std::async from std::async in windows xp
- 引用 std::shared:ptr 以避免引用计数
- std::is_reference from std::any
- std::time_point from and to std::string
- "No suitable conversion function from 'std::string' to 'const char *' exists"
- std::chrono::time_point from std::string
- Visual accept std::string from std::byte iterator
- C++中链表的错误"Abort signal from abort(3) (sigabrt) "
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- C++ 中的"template <typename From, typename Tag> struct Alias;"是什么?
- from std::vector to adept::avector
- qt get child (Callout) from QChart
- Webassembly from Javascript
- Generate boost::uuids::uuid from boost::compute::detail::sha
- 无法使用 libtool 将 -shared 参数传递给 g++
- 什么是"Reading unbounded stream from standard input (Memory Management)"的例子
- Calling C++ dll from python
- 为什么我会收到"invalid conversion from 'Queue*/Stack*' to 'int'"错误消息?
- std::chrono 在从 main 或 from 类方法使用时给出不同的值