enable_shared_from_this 在使用 shared_ptr 从 unique_ptr 到基础 class 时未初始化。为什么?

enable_shared_from_this not initialized while using shared_ptr from unique_ptr to base class. why?

我有这个代码:

#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.

使用的弱引用

完全按照设计工作。

您可以使用此 create 函数将由 test 构建的共享指针转换为 base

static std::shared_ptr<base> create(std::string text) {
    return std::shared_ptr<test>(new test(std::move(text)));
}

否则不行
enable_shared_from_this 按预期工作,但请考虑 this:

std::enable_shared_from_this allows an object t that is currently managed by a std::shared_ptr named pt to safely generate additional std::shared_ptr instances pt1, pt2, ... that all share ownership of t with pt.

在您的代码中,您没有从 test 中创建任何 shared_pointer
上面的 create 函数完成了这项工作。