c++ - 使用从 unique_ptr 到基类的 shared_ptr 时,enable_shared_from_this 未初始化。为什么?

标签 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:
  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/

相关文章:

c++ - 为什么 std::tr1::shared_ptr<>.reset() 如此昂贵?

c++ - 将 std::unique_ptr 插入 std::set

c++ - facebook api过度休息得到不正确的签名<error_code> 104

c++ - 为什么 `is_­destructible` 使用 `declval<U&>().~U()` 而不是 `declval<U>().~U()` 定义?

c++ - C++/Qt - 内存分配如何工作?

c++ - 具体类型的 unique_ptr

c++11 - unique_ptr<Derived> 到 unique_ptr<Base> 是否自动向上转换?

MinGW 的 C++ 链接器编程错误

C++ 如何使用 std::cout 停止输出 5.0 等数字的小数和零

c++ - 新图的深拷贝构造函数