0

I have the following class as an example:

#include <iostream>

class MyClass {
 private:
  double value{0};

 public:  
  explicit MyClass(double value) : value(value){};

  MyClass(const MyClass&) = delete;
  MyClass(MyClass&&) = delete;
  MyClass& operator=(MyClass&&) = delete;

  double getValue(){return value;}
};

int main(void){
    MyClass c1(100.0);               // Version 1
    MyClass c2 = MyClass(200.0);     // Version 2

    std::cout << c1.getValue() << std::endl;
    std::cout << c2.getValue() << std::endl;

}

I've learned that // Version 1 of // Version 2 is preferable because // Version 2 calls the copy constructor.

That's why I deleted the copy constructor and still // Version 2 works. Thus, no copy constructor is called.

Which operator of MyClass is called by // Version 2?

Why is // Version 1 preferable to // Version 2?

Marten Bauer
  • 3,099
  • 5
  • 22
  • 18
  • 1
    The code is valid starting from C++17, because C++17 has "guaranteed copy elision". I.e. the compiler is required to be smart enough to detect that `MyClass c2 = MyClass(200.0);` is not really different from `MyClass c2(200.0);` and create the object directly without copying, and thus a copy constructor is not needed. – HolyBlackCat Apr 03 '19 at 17:05
  • *"Why is Version 1 preferable to Version 2?"* In C++17 some people prefer it because it's shorter. Prior to C++17 version 2 seems to require a copy/move constructor even if it's optimized away (which is what any decent compiler should do), so that's another reason to not use it. – HolyBlackCat Apr 03 '19 at 17:09

0 Answers0