1

I have a doubt about the structure of std::vector

If there are some class called foo.

I will write down some code for explanation.

class foo
{
  //do something...
};

void main(void)
{
  foo a;
  std::vector<std::shared_ptr<foo>> foo_list;

  //Is it right? If not how can I do that?
  foo_list.push_back(a); 
}

Like this example, If the smart pointer was in vector, How can I put in original class in vector?

Deduplicator
  • 41,806
  • 6
  • 61
  • 104
mimic
  • 59
  • 6
  • do you mean that a have to make heap pointer using make_shared? – mimic Oct 22 '19 at 22:55
  • If I have std::vector how can I put my class variable put in the vector?. It is my real question – mimic Oct 22 '19 at 23:02
  • If you don't know how to use a `shared_ptr`, then how do you know that you should do a vector of shared pointers instead of a vector of objects? – Phil1970 Oct 23 '19 at 03:59

1 Answers1

3

foo_list is a collection of std::shared_ptr<foo> (that is shared pointers to foo objects).

foo_list.push_back(a) is attempting to add a foo instance to foo_list - obviously this won't work because the types are different (one is a shared pointer the other isn't)

You need something like:

auto a = std::make_shared<foo>();
foo_list.push_back(a); 
John3136
  • 27,345
  • 3
  • 44
  • 64