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
260 views
in Technique[技术] by (71.8m points)

c++ - Are returned locals automatically xvalues

Following on from a comment I made on this:

passing std::vector to constructor and move semantics Is the std::move necessary in the following code, to ensure that the returned value is a xvalue?

std::vector<string> buildVector()
{
  std::vector<string> local;

  // .... build a vector

  return std::move(local);
}

It is my understanding that this is required. I have often seen this used when returning a std::unique_ptr from a function, however GManNickG made the following comment:

It is my understanding that in a return statement all local variables are automatically xvalues (expiring values) and will be moved, but I'm unsure if that only applies to the returned object itself. So OP should go ahead and put that in there until I'm more confident it shouldn't have to be. :)

Can anyone clarify if the std::move is necessary?

Is the behaviour compiler dependent?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're guaranteed that local will be returned as an rvalue in this situation. Usually compilers would perform return-value optimization though before this even becomes an issue, and you probably wouldn't see any actual move at all, since the local object would be constructed directly at the call site.

A relevant Note in 6.6.3 ["The return statement"] (2):

A copy or move operation associated with a return statement may be elided or considered as an rvalue for the purpose of overload resolution in selecting a constructor (12.8).

To clarify, this is to say that the returned object can be move-constructed from the local object (even though in practice RVO will skip this step entirely). The normative part of the standard is 12.8 ["Copying and moving class objects"] (31, 32), on copy elision and rvalues (thanks @Mankarse!).


Here's a silly example:

#include <utility>

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

Foo f(Foo & x)
{
    Foo y;

    // return x;         // error: use of deleted function ‘Foo::Foo(const Foo&)’
    return std::move(x); // OK
    return std::move(y); // OK
    return y;            // OK (!!)
}

Contrast this with returning an actual rvalue reference:

Foo && g()
{
    Foo y;
    // return y;         // error: cannot bind ‘Foo’ lvalue to ‘Foo&&’
    return std::move(y); // OK type-wise (but undefined behaviour, thanks @GMNG)
}

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

1.4m articles

1.4m replys

5 comments

57.0k users

...