std::bad_weak_ptr对象构造后shared_from_this异常
std::bad_weak_ptr exception in shared_from_this after object construction
我有一个类似于以下内容的类定义:
class A : std::enable_shared_from_this<A> {
public:
static std::shared_ptr<A> create() {
return std::shared_ptr<A>(new A());
}
void f() {
shared_from_this();
}
private:
A() { }
};
它的用法类似于:
std::shared_ptr<A> pt = A::create();
pt->f();
尽管在创建shared_ptrpt
后调用了对 shared_from_this(( 的调用,但对f()
的调用仍会导致引发bad_weak_ptr
异常。在gdb
中运行它会确认异常是在对f()
的调用中引发的,而不是在我未在此处包含的由讲师调用的某些代码中引发的。
std::enable_shared_from_this<A>
必须是公共基地。当shared_ptr
构造函数看到你派生自enable_shared_from_this
时,它会在enable_shared_from_this
对象中存储自身的弱副本。如果继承不是公共的,则不会发生这种情况,并且存储在enable_shared_from_this
中的weak_ptr
将为 null,从而导致bad_weak_ptr
异常,shared_from_this
稍后尝试从中构造shared_ptr
。
此处需要公共继承。因为它是A类,所以它不是默认的。看到异常/bad_weak_ptr的原因也是如此。
相关文章:
- 如何解决"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 类方法使用时给出不同的值