dimanche 2 août 2015

Explicit copy constructor and uniform initialization

Explicit copy constructors disallow something like Foo foo = bar;, and enforce the copy usage as Foo foo(bar);. However, I tried replacing the copy initialization with braces, like so

struct Foo
{
    Foo() = default;
    explicit Foo(const Foo&) = default;
};

int main()
{
    Foo x;
    Foo y{x}; // error here
}

and I am getting the error (g++5.1)

error: no matching function for call to 'Foo::Foo(Foo&)'

or (clang++)

error: excess elements in struct initializer

Removing the explicit makes the code compilable. What's going on here? Is the uniform initialization considered as an initializer-list constructor (which trumps all others)? But if that's the case, why does the program compile when the copy constructor is non-explicit?

Aucun commentaire:

Enregistrer un commentaire