1

I saw this question but it doesn't really resolve my Problem.

Following is my class and I want to initialize the unique_ptr vector from initializer list:

class MyClass
{
public:
    vector<unique_ptr<int>> vec2;
    MyClass();
};

MyClass::MyClass()  :
vec2{
    move(make_unique<int>(30)), // Doesn't work
    move(make_unique<int>(20))} // Doesn't work
{

    unique_ptr<int> myPtr= make_unique<int>(30);  // this works
    unique_ptr<int> myPtr2= make_unique<int>(20); // this works

    vec2.push_back(move(myPtr));  // this works
    vec2.push_back(move(myPtr2)); // this works
} 

Following is the error:

error: use of deleted function β€˜std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/7/memory:80:0,
             from test.cpp:3:
/usr/include/c++/7/bits/unique_ptr.h:388:7: note: declared here
   unique_ptr(const unique_ptr&) = delete;

What I know is that when calling move the move constructor will be called, I mean unique_ptr(const unique_ptr&&) instead of unique_ptr(const unique_ptr&) so why in the error message is saying unique_ptr(const unique_ptr&) = delete;

Mouin
  • 1,025
  • 4
  • 19
  • 33
  • The `std::move` calls here don't change anything. `make_unique(30)` is a prvalue, so it already binds to an rvalue reference. – chris Jul 03 '19 at 20:59
  • tl;dr - you can't do that. `std::initializer_list` constructors copy the arguments, which is impossible regarding `std::unique_ptr`. The answer below the question you linked mentiones that. Voting to close as a duplicate for that very question – Fureeish Jul 03 '19 at 21:02

0 Answers0