gpt4 book ai didi

c++ - 在 C++ 中,返回时使用 move 操作是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 20:01:46 24 4
gpt4 key购买 nike

我正在通读 Bjarne Stroustrup 的 The C++ Programming Language(第 4 版)和第 1 页。 516 他说:

How does the compiler know when it can use a move operation rather than a copy operation? In a few cases, such as for a return value, the language rules say that it can (because the next action is defined to destroy the element)

也在第517 他说:

[The object] has a move constructor so that "return by value" is simple and effecient as well as "natural"

如果 return 总是使用 move 操作,那么为什么像下面这样的东西不起作用?

#include <vector>
#include <assert.h>

using namespace std;

vector<int> ident(vector<int>& v) {
return v;
};

int main() {
vector<int> a {};
const vector<int>& b = ident(a);
a.push_back(1);
assert(a.size() == b.size());
}

ab 不应该指向相同的对象吗?

最佳答案

引自http://eel.is/c++draft/class.copy.elision :

In the following copy-initialization contexts, a move operation might be used instead of a copy operation:

(3.1) If the expression in a return statement ([stmt.return]) is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression, or

(3.2) if the operand of a throw-expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one),

overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.

因此,如果您返回一个自动(局部)变量:

vector<int> ident() {
vector<int> v;
return v;
};

然后,v 将在 return 语句中被视为一个右值,因此,返回值将初始化为 move 构造函数。

但是,您的代码不满足这些条件,因为您的 ident 中的 v 不是自动变量。因此,它在 return 语句中被视为一个左值,并且返回值由函数参数引用的 vector 中的复制构造函数初始化。

这些规则是很自然的。想象一下,允许编译器从 return 语句中的所有左值 move 。幸运的是,只有当他们知道左值将被销毁时,他们才能这样做,这适用于在 return 语句的上下文中通过值传递的自动变量和参数。

关于c++ - 在 C++ 中,返回时使用 move 操作是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53095341/

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