Reputation: 91
class MyClass
{
public:
int a;
MyClass(int r): a(r) {}
MyClass(const MyClass& ref)
{
cout << "Copy Constructor\n";
a= ref.a;
}
};
int main()
{
MyClass obj(5);
MyClass obj1(MyClass(5)); //Case 1
MyClass obj2(obj); //Case 2
return 0;
}
Why the copy constructor is invoked in Case 2, not in Case 1. In case 1 a temporary object is passed as argument.
Upvotes: 1
Views: 306
Reputation: 136266
In MyClass obj1(MyClass(5));
the compiler elides the temporary object MyClass(5)
because it is allowed to.
In particular, C++ standard 2014 §12.8 para 31, defines cases when copy elision can be performed:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects... This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
- 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.
Upvotes: 3