Reputation: 720
So I am working on a transformation from an OO-language with garbage collection capabilities to C++. To start out I want to wrap all objects in shared pointers to solve the memory de-allocation issue. Right now I am trying to wrap a vector in a shared pointer and initializing the vector directly. See the issue below. Why is it not working and, if possible, how do I make it work?
vector<int> vec({ 6, 4, 9 }); // Working
shared_ptr<vector<int>> vec = make_shared<vector<int>>({ 6, 4, 9 }); // Not working
Sorry for not including the error, the error I am getting is marked at (make_shared) and printed as:
no instance of function template "std::make_shared" matches the argument list
argument types are: ({...})
Thanks for any answers!
Upvotes: 12
Views: 9177
Reputation: 13288
Brace initializer list cannnot be used in most type deduction contexts.
If you explicitly specify the type it works:
std::shared_ptr<std::vector<int>> vec = std::make_shared<std::vector<int>>(std::vector<int>{ 6, 4, 9 });
Upvotes: 13
Reputation: 15334
make_shared does not support non-explicit initializer lists. You could make use of the fact that auto
can deduce an initializer list:
auto init = { 6, 4, 9 };
auto vec = std::make_shared<std::vector<int>>(init);
But as others have pointed out, you need to consider if you need a shared_ptr
at all, vector
manages its own memory. shared_ptr
is not free.
Upvotes: 0
Reputation: 2241
auto vec = make_shared<vector<int>>(std::initializer_list<int>{ 6, 4, 9 });
Upvotes: 3
Reputation: 249153
Initializer lists don't play well with make_shared
. For more detail, see here: std::make_shared with std::initializer_list
But probably the real solution is to not hold your vector in a smart pointer at all--not everything deserves a smart pointer anyway. But if you want to stick with it, this should work:
shared_ptr<vector<int>> vec(new vector<int>({ 6, 4, 9 }));
Upvotes: 0