Search code examples
c++classc++11shared-ptrstdvector

I have a question about std::vector<shared_ptr>


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?


Solution

  • 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);