我对下面的一段代码有疑问。函数 fun1
和 fun2
都是一样的。在一个中,我声明了一个局部变量,在另一个中,一个变量通过参数传递。那么为什么在 fun1 的情况下不调用复制构造函数。
#include<stdio.h>
#include<iostream>
using namespace std;
class A
{
public:
A()
{
printf("constructor\n");
}
A(const A&)
{
printf("copy cons\n");
}
~A()
{
printf("destructor\n");
}
};
A fun1()
{
A obj;
return obj;
}
A fun2(A obj)
{
return obj;
}
int main()
{
A a=fun1();
printf("after fun1\n");
A b;
A c = fun2(b);
}
输出
constructor
after fun1
constructor
copy cons
copy cons
destructor
destructor
destructor
destructor
最佳答案
因为Named Return Value Optimization ,这是编译器对您的代码执行的优化。它认识到函数 fun1() 的返回类型与 fun1() 中的临时对象(类型 A)相同的事实,因此它不会创建它的拷贝(不调用复制构造函数)返回声明。
您可以尝试编译您的代码without optimization然后查看复制构造函数是否被调用。如果您使用的是 gcc 编译器,用于关闭优化的编译器标志是“-O0”。
关于c++ - 局部变量和作为参数传递的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14191971/