在 C++ 中创建向量的 shared_ptr

Creating a shared_ptr of vector in C++

在现代 C++ 中,我们可以像这样初始化一个向量:

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

但是如果我尝试创建一个指向向量的智能指针,这将无法编译:

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

有没有比创建后求助于 push_back 更好的选择?

您也可以通过直接在参数中创建另一个向量来移动它:

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

这是有效的。看起来编译器不能在没有直接指定 initializer_list.

的情况下在 make_unique 参数中吃掉 {}

小修改 - 使用 MSVC 2015