C++ 从启用共享时,此选项在使用从唯一到基类的共享时未初始化。为什么?
我有以下代码:C++ 从启用共享时,此选项在使用从唯一到基类的共享时未初始化。为什么?,c++,shared-ptr,unique-ptr,C++,Shared Ptr,Unique Ptr,我有以下代码: #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:
#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;
}
你还指望什么?您正在使用
共享\u ptr
。Base不是从从\u this
启用\u shared\u继承的,因此它的共享指针不能初始化来自\u this的shared\u使用的弱引用
完全按照设计工作。您可以使用此创建
功能将由测试构建的共享指针强制转换为一个指向基的指针:
static std::shared_ptr<base> create(std::string text) {
return std::shared_ptr<test>(new test(std::move(text)));
}
static std::shared\u ptr create(std::string text){
返回std::shared_ptr(新测试(std::move(text));
}
否则,它将无法工作。
<代码> EnabyLySydRoFux< >按预期运行,但考虑:
std::enable_shared_from_这允许当前由名为pt的std::shared_ptr管理的对象t安全地生成其他std::shared_ptr实例pt1、pt2等,所有这些实例都与pt共享t的所有权
在您的代码中,您没有在测试中创建任何共享\u指针
上面的create
函数完成了这项工作。尽管我之前说过工厂函数应该返回一个唯一的\u ptr
,但它确实要求指针在工厂返回点尚未共享。如果您的类继承了此
的共享,那么当工厂返回时,已经有两个指针。事实上,请联系建议您一起使用unique\u ptr
和shared\u的人,告诉他们有一个例外。
static std::shared_ptr<base> create(std::string text) {
return std::shared_ptr<test>(new test(std::move(text)));
}