为什么不调用复制构造函数? [英] Why is the copy constructor not called?

查看:144
本文介绍了为什么不调用复制构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class MyClass
{
public:
  ~MyClass() {}
  MyClass():x(0), y(0){} //default constructor
  MyClass(int X, int Y):x(X), y(Y){} //user-defined constructor
  MyClass(const MyClass& tempObj):x(tempObj.x), y(tempObj.y){} //copy constructor

private:
  int x; int y;
};

int main()
{
  MyClass MyObj(MyClass(1, 2)); //user-defined constructor was called.
  MyClass MyObj2(MyObj); //copy constructor was called.
}



在第一种情况下,当 MyClass 2)调用用户定义的构造函数并返回一个对象,我期待 MyObj 调用复制构造函数。为什么不需要为 MyClass

In the first case, when MyClass(1, 2) calls the user-defined constructor and returns an object, I was expecting MyObj to call the copy constructor. Why it doesn't need to call the copy constructor for the second instance of MyClass?

推荐答案

只要创建一个临时对象,仅仅为了复制和随后销毁临时对象,就允许编译器完全删除临时对象,并直接在接收者中构造结果(即直接在假定的对象中)接收副本)。

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));

可以转换为

MyClass MyObj(1, 2);

此过程称为复制操作的检测。它在语言标准的12.8 / 15中描述。

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

这篇关于为什么不调用复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆