我有这个代码:
#include <iostream>
#include <memory>
#include <string>
class base {
public:
virtual void method() = 0;
virtual ~base() = default;
};
class test: public base, public std::enable_shared_from_this<test> {
private:
std::string text;
public:
test(std::string text): text(std::move(text)) {}
~test() = default;
virtual void method() override {
std::cout << "text: " << text;
std::cout << " this: " << this->shared_from_this().get() << std::endl;
}
static std::unique_ptr<base> create(std::string text) {
return std::unique_ptr<base>(new test(std::move(text)));
}
};
static auto create_test(std::string text) {
return test::create(std::move(text));
}
int main(int argc, char* argv[]) {
std::shared_ptr<base> shared = create_test("some text");
shared->method();
return 0;
}
当我运行这个程序时,我得到异常“bad_weak_ptr”。 你能解释一下为什么“enable_shared_from_this”没有被初始化吗?
当我更改 unique_ptr<base>
的实例时至 unique_ptr<test>
它有效。
$ ./test
terminate called after throwing an instance of 'std::bad_weak_ptr'
what(): bad_weak_ptr
text: some textAborted (core dumped)
最佳答案
您还期待什么?您正在使用 shared_ptr<base>
. Base 不是继承自 enable_shared_from_this
, 所以它的共享指针不能初始化 shared_from_this
使用的弱引用.
完全按照设计工作。
关于c++ - 使用从 unique_ptr 到基类的 shared_ptr 时,enable_shared_from_this 未初始化。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38021504/