gpt4 book ai didi

c++ - 为什么在返回 LOCAL 变量时不调用复制构造函数

转载 作者:搜寻专家 更新时间:2023-10-31 00:36:50 24 4
gpt4 key购买 nike

我不明白为什么当我试图返回一个在函数中定义的局部变量时没有调用复制构造函数。请参阅以下简化示例:

#include <iostream>
using namespace std;

class X {
public:
X() { cout << "Default Constructor" << endl; }
X(const X&) { cout << "Copy Constructor" << endl; }
};

X f(X x) { return x; }

X g() {
X y;
return y;
}

int main() {
cout << "First create an object" << endl;
X a;
cout << "Call f()" << endl;
f(a);
cout << "Call g()" << endl;
g();
}

编译后的程序输出如下

First create an object
Default Constructor
Call f()
Copy Constructor
Copy Constructor
Call g()
Default Constructor

我明白调用 f() 时发生了什么,但不知道为什么 g() 调用中的 return y 会不触发复制构造函数。

最佳答案

编译器优化掉返回拷贝。这称为 NRVO(命名返回值优化)。

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

即使复制构造函数有副作用,编译器也可以这样做。

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects.

也就是说,如果你给你的复制/移动构造函数带来副作用,你的程序就会有多个有效的执行路径,这取决于你的编译器是否想要优化。

关于c++ - 为什么在返回 LOCAL 变量时不调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20837691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com