相关疑难解决方法(0)

当按值返回时,值参数是否隐式移动?

考虑以下功能:

Foo foo(Foo x)
{
    return x;
}
Run Code Online (Sandbox Code Playgroud)

return x调用复制构造函数还是移动构造函数?(让我们把NRVO留在这里.)

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

struct Foo
{
    Foo() = default;
    Foo(const Foo&) = delete;
    Foo(Foo&&) = default;
};
Run Code Online (Sandbox Code Playgroud)

如果在按值返回值参数时调用了移动构造函数,则一切都应该没问题.但是当前的g ++编译器抱怨return x以下错误消息:

error: deleted function 'Foo::Foo(const Foo&)'
Run Code Online (Sandbox Code Playgroud)

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

c++ rvalue-reference move-semantics c++11

22
推荐指数
2
解决办法
567
查看次数

标签 统计

c++ ×1

c++11 ×1

move-semantics ×1

rvalue-reference ×1