Constructor
Constructor

Reputation: 7473

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).

Upvotes: 3

Views: 102

Answers (1)

Martin Hierholzer
Martin Hierholzer

Reputation: 930

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.

Upvotes: 7

Related Questions