Reputation: 14318
I'm trying to use the "fill" version of the std::vector constructor. It takes the number of elements as the first argument, and const value_type& as the second argument:
#include <vector>
int main()
{
std::vector<int> v(100, 7);
// Works, creates vector with 100 elements of int 7.
}
However I can't seem to make this work with unique_ptrs:
#include <vector>
#include <memory>
int main()
{
std::vector<std::unique_ptr<int>> v1(100, std::unique_ptr<int>());
std::vector<std::unique_ptr<int>> v2(100, std::make_unique<int>());
}
Both don't work with unique_ptrs. The error I get from Visual Studio 2017 is:
Error C2280 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
Considering the second argument takes const reference to the type contained in the vector, I expected std::unique_ptr() or std::make_unique() to simply work as the second argument. I know they're both temporaries, but seeing as the argument is const reference, it should accept it, why way it accepted it accepted integer 7 for the argument in my first example that works.
Also, std::unique_ptr() looks very close to "most vexing parse" however the examples at cppreference.com use it:
// Use the default constructor.
std::unique_ptr<Vec3> v1 = std::make_unique<Vec3>();
As I said, this looks something like "most vexing parse", being a function signature for a function taking no arguments and returns a std::unique_ptr< Vec3 >
Upvotes: 2
Views: 720
Reputation: 14895
The std::vector
constructor you are attempting to use has to copy the input value provided in order to populate the vector to the requested size. Not being able to copy a std::unique_ptr
is one of its most important features, so you shouldn’t be surprised that your code does not work.
If you drop the second argument, each value in the vector will be constructed with std::unique_ptr
's default constructor; thus making no copies. This is what you are trying to do anyway.
See also: How to initialize a vector of unique_ptr with null pointers?
Upvotes: 5