【问题标题】:Understanding copy constructor in C++ [duplicate]了解 C++ 中的复制构造函数 [重复]
【发布时间】:2015-08-09 20:53:36
【问题描述】:

我试图理解 C++ 中复制构造函数的概念。我编写了以下程序:

#include<iostream>
using namespace std;

class Box{
    private:
        int d;
    public:
        Box(int i){
            cout << "Constructor" << endl;
            d = i;
        }
        Box(const Box &old){
            cout << "Copy Constructor" << endl;
            d = old.d;
        }
        int getd(){
            return d;
        }
        ~Box(){
            cout << "Destructor" << endl;
        }
        Box operator+(const Box& op){
            Box c(15);
            c.d = d + op.d;
            return c;
        }
};

int main(){
    Box a(10);
    Box b = a;
    Box c = a+b;
    cout << c.getd() << endl;
    return 0;
}

这个程序的输出如下:

Constructor
Copy Constructor
Constructor
20
Destructor
Destructor
Destructor

我不明白为什么 main 函数的第三行没有调用复制构造函数。我认为应该调用复制构造函数,因为operator+ 函数按值返回。

【问题讨论】:

  • 为什么用代码格式标记“复制构造函数”?很奇怪。
  • 我试图观察这些函数是如何被调用的。
  • 不,我的意思是,在您的问题正文中。我会改正的。

标签: c++ operator-overloading copy-constructor


【解决方案1】:

编译器正在优化此处的复制构造函数调用,因为标准明确允许“省略”该复制。这样的副本有什么意义,真的吗?

不过,您是绝对正确的,因为它是调用复制构造函数的机会,而编译器可以 做到这一点。事实上,标准确实要求调用复制构造函数在这里是有效的。

【讨论】:

  • 编译器可以调用第三行的move进行优化。
  • @jaklucky:OP 的类型没有移动构造函数 ([C++11: 12.8/9])。
  • 如果是这样,这不是一个可选的优化。如果它没有省略,编译器必须调用移动构造函数,而不是它适用的复制构造函数。
  • ...使它根本不是真正的“优化”。
猜你喜欢
  • 2015-07-15
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 2014-01-19
  • 2018-11-01
  • 2012-02-04
相关资源
最近更新 更多