Creating a shared_ptr of vector in C++ [duplicate]

2019-04-22 09:15发布

问题:

This question already has an answer here:

  • Calling initializer_list constructor via make_unique/make_shared 2 answers

In modern C++ we can initialize a vector like this:

std::vector<int> v = { 1, 2, 3, 4, 5 };

But if I try creating a smart pointer to a vector, this won't compile:

auto v = std::make_shared<std::vector<int>>({ 1, 2, 3, 4, 5 });

Is there any better alternative than resorting to push_backs after creation?

回答1:

auto v = std::make_shared<std::vector<int>>(std::initializer_list<int>{ 1, 2, 3, 4, 5 });

This is working. Looks like compiler cannot eat {} in make_unique params without direct specification of initializer_list.

Minor edit - used MSVC 2015



回答2:

You can alternatively do it by creating another vector directly in parameter in order to move it:

auto v = std::make_shared<std::vector<int>>(std::vector<int>({ 1, 2, 3, 4, 5 }));