简体   繁体   中英

Why copy constructor is not called when pass temporary object

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM