Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

c++ - Are value parameters implicitly moved when returned by value?

Consider the following function:

Foo foo(Foo x)
{
    return x;
}

Will return x invoke the copy constructor or the move constructor? (Let's leave NRVO aside here.)

To investigate, I wrote a simple Foo class that is only movable but not copyable:

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

If the move constructor were invoked when returning value parameters by value, all should be fine. But the current g++ compiler complains about return x with the following error message:

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

If I replace return x with return std::move(x), everything is fine. From this I conclude that moving from value parameters must be done explicitly if desired. Is g++'s behavior conforming or not?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If there is a move ctor for Foo, it should be selected.

Function parameters are explicitly excluded from copy elision in return statements (FDIS §12.9p31, first bullet):

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

However, the next paragraph explicitly brings move ctors back into consideration:

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. …

(Emphasis is mine in both quotes.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...