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?
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.
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.
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 ).
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.
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 }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With