0

i have this code

#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;
}

but i get following error

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

so how can i add to list_ when i construct a class without call external function after initilization?

Mohsen Zahraee
  • 3,309
  • 5
  • 31
  • 45
  • 2
    You cannot call shared_from_this() in the constructor because enable_shared_from_this needs an object of Foo to create a shared_ptr, and that hasn't yet been created: https://stackoverflow.com/questions/31924396/why-shared-from-this-cant-be-used-in-constructor-from-technical-standpoint – jignatius Sep 25 '19 at 07:16

1 Answers1

0

The line

Foo f;

creates an instance on the stack and shared pointers to stack objects are not allowed.

Second thing is that the constructor of Foo accesses the ´this´ pointer while construction is not finished - you get an exception that the object is deleted (here not already constructed). (where storing shared ´this´ pointers in a member is generally not a good idea).

So the solution for you could be:

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;
}
mommos
  • 189
  • 5
  • i dont want to create object on heap! – Mohsen Zahraee Sep 25 '19 at 06:34
  • @sayyedmohsenzahraee If you don't want to create an object on heap, why then do you need shared pointers? Why simply not store raw pointers in your vector, if the objects are destroyed automatically? Note that `std::enable_shared_from_this` is intended for [objects managed by `std::shared_ptr`](https://en.cppreference.com/w/cpp/memory/enable_shared_from_this). – Daniel Langr Sep 25 '19 at 06:55