将此类的智能指针附加到成员std :: vector

问题描述 投票:0回答:1

我有此代码

#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class Foo : public std::enable_shared_from_this<Foo> {
 public:
  Foo() { list_.push_back(shared_from_this()); }

 private:
  static std::vector<shared_ptr<Foo>> list_;
};
std::vector<shared_ptr<Foo>> Foo::list_;

int main() {
  Foo f;

  cout << "Hello World!" << endl;
  return 0;
}

但我收到以下错误

terminate called after throwing an instance of 'std::bad_weak_ptr'
  what():  bad_weak_ptr
Press <RETURN> to close this window...

所以当初始化后在不调用外部函数的情况下构造一个类时,如何添加到list_

c++ vector smart-pointers
1个回答
0
投票

Foo f;

在堆栈上创建一个实例,并且不允许共享指向堆栈对象的指针。

第二件事是Foo的构造函数在构造未完成时访问this指针-您会得到一个例外,即该对象已删除(此处尚未构造)。 (在成员中存储共享的“ this”指针通常不是一个好主意)。

所以您的解决方案可能是:

class Foo 
  : public std::enable_shared_from_this<Foo> 
{
public:
  Foo() 
  {
  }
  void push()
  {
    list_.push_back(shared_from_this());
  }
private:
  static std::vector<shared_ptr<Foo>> list_;
};
std::vector<shared_ptr<Foo>> Foo::list_;

int main()
{
  std::shared_ptr<Foo> foo = std::make_shared<Foo>();
  foo->push();
  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.