Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 910
Crossfire Avatar asked Jan 13 '16 14:01

Crossfire


People also ask

Is it possible to create a vector of shared pointers to contactobjects?

I believe that I can either create a vector of vector of shared pointers to Contactobjects, vector<vector<shared_ptr >> prtContacts(where I have left off std::for ease of viewing), so that prtContacts will contain a vector of shared pointers to the contacts of the ith particle.

What is shared_ptr in C++?

The last remaining shared_ptr object owning the pointer is assigned with some other pointer. shared_ptr is present in the std namespace in the <memory> header file of the standard C++. In this post, we will learn how we can write our own shared_ptr class.

Can I use vector<unique_ptr<MyClass> instead of shared_ptr?

vector<shared_ptr<MyClass>> MyVector; should be OK. But if the instances of MyClass are not shared outside the vector, and you use a modern C++11 compiler, vector<unique_ptr<MyClass>> is more efficient than shared_ptr (because unique_ptr doesn't have the ref count overhead of shared_ptr ).

Is it possible to swap a shared pointer in a vector?

Along that point, it may make sense to wrap your entire std::vector. class MyClassCollection { private : std::vector<MyClass> collection; public : MyClass& at (int idx); //... }; So you can safely swap out not only the shared pointer but the entire vector.


2 Answers

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

like image 81
Starl1ght Avatar answered Oct 18 '22 18:10

Starl1ght


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 }));
like image 22
Aracthor Avatar answered Oct 18 '22 19:10

Aracthor