gpt4 book ai didi

c++ - 按值返回时,值参数是否隐式 move ?

转载 作者:IT老高 更新时间:2023-10-28 21:39:49 24 4
gpt4 key购买 nike

考虑以下函数:

Foo foo(Foo x)
{
return x;
}

return x 会调用复制构造函数还是 move 构造函数? (让我们把 NRVO 放在一边。)

为了调查,我写了一个简单的 Foo 类,它只能 move 但不能复制:

struct Foo
{
Foo() = default;
Foo(const Foo&) = delete;
Foo(Foo&&) = default;
};

如果在按值返回值参数时调用了 move 构造函数,一切都应该没问题。但是当前的 g++ 编译器提示 return x 并带有以下错误消息:

error: deleted function 'Foo::Foo(const Foo&)'

如果我将 return x 替换为 return std::move(x),一切都很好。由此我得出结论,如果需要,必须明确地从值参数 move 。 g++的行为符合与否?

最佳答案

如果有 Foo 的 move ctor,则应该选择它。

函数参数在返回语句中被明确排除在复制省略之外(FDIS §12.9p31,第一个项目符号):

  • 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)

但是,下一段明确地重新考虑了 move ctors:

When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. …

(两个引号中的重点是我的。)

关于c++ - 按值返回时,值参数是否隐式 move ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6009004/

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