Why is the copy constructor not called?

后端 未结 4 1376
醉酒成梦
醉酒成梦 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

    Whenever a temporary object is created for the sole purpose of being copied and subsequently destroyed, the compiler is allowed to remove the temporary object entirely and construct the result directly in the recipient (i.e. directly in the object that is supposed to receive the copy). In your case

    MyClass MyObj(MyClass(1, 2));
    

    can be transformed into

    MyClass MyObj(1, 2);
    

    even if the copy constructor has side-effects.

    This process is called elision of copy operation. It is described in 12.8/15 in the language standard.

提交回复
热议问题