std::initializer_list and move semantics.

Hello,

I am having problems with using initializer_list when I am passing object that only support move constructor and move assigment.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <memory>
#include <vector>

struct MyStruct
{

    MyStruct(const MyStruct&) = delete;
    MyStruct& operator=(const MyStruct&) = delete;

    MyStruct(MyStruct &&my_struct)
    { 
        numbers = std::move(my_struct.numbers);
    }

    MyStruct& operator=(MyStruct&& my_struct)
    {
        numbers = std::move(my_struct.numbers);
        return *this;        
    }

    MyStruct(std::initializer_list<int> numbers_)
    {
        numbers = std::make_unique<std::vector<int>>(numbers_);
    };

    std::unique_ptr<std::vector<int>> numbers;
};

using Structs = std::vector<MyStruct>;

int main()
{
    MyStruct my_struct({1, 2, 3});
    Structs structs{std::move(my_struct)}; //Error here: "use of deleted function 'MyStruct::MyStruct(const MyStruct&)"
    return 0;
}


I guess there is no way around it?
std::initializer_list is unfortunately immutable and doesn't support moves.

You will have to insert the MyStruct objects into the vector some other way.

1
2
3
4
5
6
Structs structs;

MyStruct my_struct({1, 2, 3});
structs.push_back(std::move(my_struct)); // OK

structs.push_back(MyStruct{1, 2, 3}); // OK 
Last edited on
Thanks for clarification :)
Topic archived. No new replies allowed.