c++c++11defaultcopy-constructordefault-copy-constructor

2 defaulted copy constructors: is it possible?


Is the following program ill-formed?

struct Foo
{
    Foo(Foo&) = default;

    Foo(const Foo&) = default;
};

int main() 
{
}

It successfully compiles with clang++ 3.8.0 and g++ 6.3.0 (compiler flags are -std=c++11 -Wall -Wextra -Werror -pedantic-errors).


Solution

  • Why should this be ill-formed? You define two copy constructors, one which expects a non-const argument and the other which can use a const argument. You then tell the compiler it should use its default implementation for these two constructors. Unless the compiler has a reason to eliminate the default copy constructors, you could also delete those two lines and would get the same result. Also I think the first version is redundant, since the default implementation should anyway be fine with a const argument. Still defining both is legal, since you might want to do something different in the two cases.