Should explicit keyword be used for move constructors?

This code does not compile. But if I remove the explicit keyword from the move constructor then it works. Why?

struct Bar {
    Bar() {}
    explicit Bar(const Bar& x) {}
    explicit Bar(Bar&& x) {}

Bar bar() {
    Bar x;
    return x;

The compilation error is:

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

>Solution :

The return statement copy-initializes the return value from the operand.

Copy-initialization doesn’t consider explicit constructors. But explicit doesn’t change that the constructors you defined are copy and move constructors. Therefore no other implicit constructors will be declared.

In effect, there is no viable constructor left to construct the return value.

If you remove the explicit on either of the constructors, there will be a viable constructor to construct the return value and it will compile. The move constructor will be preferred if it is not explicit, because of the special semantics of return statements.

Copy and move constructors should usually not be explicit.

Leave a Reply