3
#include <iostream>
#include <initializer_list>

class MyArray {
    int* array;
public:
    MyArray(){}
    MyArray(std::initializer_list<int>& v) {
        array = new int[v.size()];
        int index = 0;
        for (auto element : v) {
            array[index] = element;
            index++;
        }
    }

    ~MyArray()
    {
        delete[] array;
    }
};

int main() {
    MyArray object{ 2,4,2,2 };
}

This is my first time working with std::initializer for object list initialization. I have created a an array that is initialized using the MyArray constructor. i don't know where am i going wrong. i created an object that matches the argument list, ie a constructor that takes an initializer list.

kira55
  • 87
  • 4

2 Answers2

3

i created an object that matches the argument list, ie a constructor that takes an initializer list.

You didn't; not quite.

You created a constructor that takes a reference to an std::initializer_list.

But one created in this manner is [possibly] a temporary that cannot bind to such a reference.

Generally you just want to take std::initializer_lists by value. That is: remove the &.

There are some examples on cppreference's article on std::initializer_list.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • i have hard time understanding the contents on cppreference, my IQ went downhill after i started learning c++. thanks for pointing out the obvious. – kira55 Dec 25 '19 at 23:11
  • It's okay, your IQ is safe: just the confusion level will go up with anything relating to this ghastly language :P – Lightness Races in Orbit Dec 25 '19 at 23:14
  • Can you also use `const` reference, to extend the life of the temporary object? – ChrisMM Dec 26 '19 at 00:00
  • 1
    @ChrisMM I guess so, but that doesn't really gain you anything over just taking a value, and is not idiomatic (probably because it doesn't really gain you anything). Have a read of _"[why is `std::initializer_list` often passed by value?](https://stackoverflow.com/q/17803475/560648)"_. – Lightness Races in Orbit Dec 26 '19 at 00:46
0

MyArray object{ 2,4,2,2 };

Actually this is invoking move assignment of MyArray. { 2,4,2,2 } is a rvalue and you can't bind it to a reference.

You need to understand what is rvalue reference and move semantics, and here is a good answer: What is move semantics?

Kejia Cui
  • 111
  • 1
  • 5