Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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&)'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading