Following code works perfectly fine (showing RVO):
struct A {
A (int) { cout << "A::A()\n"; } // constructor
A (const A&) { cout << "A::A(const A&)\n"; } // copy constructor
};
A foo () { return A(0); }
int main () {
A a = foo();
}
Output:
A::A() // --> which means copy constructor is not called
If I mark the copy constructor as explicit
:
explicit A (const A&) { ... }
Then the compiler errors out:
explicit.cpp: In function ‘A foo()’:
explicit.cpp:10:22: error: no matching function for call to ‘A::A(A)’
A foo () { return A(0); }
^
explicit.cpp:5:3: note: candidate: A::A(int)
A (int) { cout << "A::A()\n"; }
^
explicit.cpp:5:3: note: no known conversion for argument 1 from ‘A’ to ‘int’
explicit.cpp: In function ‘int main()’:
explicit.cpp:14:13: error: no matching function for call to ‘A::A(A)’
A a = foo();
^
explicit.cpp:5:3: note: candidate: A::A(int)
A (int) { cout << "A::A()\n"; }
^
explicit.cpp:5:3: note: no known conversion for argument 1 from ‘A’ to ‘int’
Why is it happening, Shouldn't the RVO work as it is?