Why is the copy constructor not called?

后端 未结 4 1372
醉酒成梦
醉酒成梦 2020-11-28 12:13
class MyClass
{
public:
  ~MyClass() {}
  MyClass():x(0), y(0){} //default constructor
  MyClass(int X, int Y):x(X), y(Y){} //user-defined constructor
  MyClass(cons         


        
4条回答
  •  温柔的废话
    2020-11-28 12:26

    The copy constructor may be elided in such a case.

    Likewise with MyClass MyObj = MyClass( 1, 2 );.

    And with

    std::string str = "hello";
    

    Such code has an implicit constructor call to convert the char* to a std::string.

    std::string str = std::string( "hello" ); // same, written more verbosely
    

    Without copy elision, the "easy" string initialization by assignment syntax would incur an additional deep copy. And that syntax is 99% equivalent to what you have.

提交回复
热议问题