简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM