This question already has an answer here:
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_back
s after creation?
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
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 }));
来源:https://stackoverflow.com/questions/34769617/creating-a-shared-ptr-of-vector-in-c