Reputation: 482
here is a class definition with 3 different constructors, one default, one integer parametrized and a copy constructor. R-value objects are created and operated on just after creation. The first two cases work as expected but in the final case two constructor invocation is expected but only the first one takes place. Why so? Following is the code.
#include <iostream>
using namespace std;
class A
{
int i;
public:
A() {cout << "In default ctor\n";};
A(int v) {cout << "Setting i in par-ctor to " << v << "\n"; i=v;}
A(const A& o) {cout << "In copy ctor, changing i to " << o.i << "\n"; i=o.i;}
void print() {cout << "i = " << i << endl;}
};
int main()
{
A o(10);
A(o).print(); // invokes copy constructor A(const A&) as expected
A(20).print(); // invokes int parametrized constructor A(int)
A(A(30)).print(); // invokes only int constructor A(int) and not copy constructor, why so?
return(0);
}
The output is:
Setting i in par-ctor to 10
In copy ctor, changing i to 10
i = 10
Setting i in par-ctor to 20
i = 20
Setting i in par-ctor to 30
i = 30
Upvotes: 0
Views: 61
Reputation: 110728
The C++ standard explicitly allows compilers to omit copies in certain situations. This is known as copy elision. One such situation is as you've shown:
when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
Note that copy elision is optional. Your compiler happens to be treating that line like A(30).print();
, but it doesn't have to.
Upvotes: 4