samedi 19 août 2017

I intend to call initializer_list constructor, and copy constructor is called beforehand if it exists: why?

The following type has three constructors. Note that one of them takes an initializer list of elements of that very same type.

struct Foo {
    Foo() {
        std::cout << "default ctor" << std::endl;
    }
    Foo(const Foo&) {
        std::cout << "copy ctor" << std::endl;
    }
    Foo(std::initializer_list<Foo>) {
        std::cout << "initializer_list<Foo>" << std::endl;
    }
};

While initializing an object using an initializer_list, I am surprised to see the copy constructor is automatically called as many times as there are elements in the initializer_list. Afterwards, the initializer_list constructor is called:

int main()
{
    Foo a;          // default ctor
    Foo b{a, a, a}; // copy ctor + copy ctor + copy ctor + initializer_list<Foo>
    return 0;
}

What are the reasons/justifications behind that behavior? Note that if Foo had no copy constructor, the initialization Foo b{a, a, a} would apparently be perfectly possible (the initializer_list constructor would be the only one called).

Full code here: http://ift.tt/2vaLCIP

Aucun commentaire:

Enregistrer un commentaire