【发布时间】:2014-01-14 06:55:50
【问题描述】:
这里是一个简单的类头文件和一个主程序。在主程序中,我认为复制构造函数在三种情况下被调用:初始化(显式复制),函数参数传值,函数传值。但是,似乎没有要求其中之一,我认为 (3) 或 (4) 在 cmets 中编号。调用哪个数字 (1) - (4)?谢谢。
X.h:
#include <iostream>
class X
{
public:
X() {std::cout << "default constructor \n";}
X(const X& x) { std::cout << "copy constructor \n";}
};
主要:
#include "X.h"
X returnX(X b) // (1) pass by value - call copy constructor?
{
X c = b; // (2) explicit copy - call copy constructor?
return b; // (3) return by value - call copy constructor?
}
int main()
{
X a; // calls default constructor
std::cout << "calling returnX \n\n";
X d = returnX(a); // (4) explicit copy - call copy constructor?
std::cout << "back in main \n";
}
输出:
default constructor
calling returnX
copy constructor
copy constructor
copy constructor
back in main
【问题讨论】:
-
允许编译器对其进行优化。
标签: c++ copy-constructor pass-by-value return-by-value