How to use move semantics with std::string during function return?

31,422

Solution 1

You are absolutely correct that the int&& GetInt() example is wrong, and is returning a reference to an object that is destroyed. However, unless I missed it, the link you posted does not actually show any code returning a reference to a local variable. Instead I see a reference to a global variable being returned, which is okay.

Here is how you use move semantics when returning:

std::string func()
{
    std::string rv;
    /* ... */
    return rv;
}

You generally should not use std::move() when returning an object. The reason for this is that moving is already implicitly allowed anytime RVO could occur, and using std::move() will suppress RVO. So using std::move() will never be better and will often be worse than just returning normally.


Again, using std::move() can be worse than simply naming the variable to be returned because it suppresses the return value optimization. The return value optimization allows for an object to be returned to the caller without needing to copy that object

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) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

— [class.copy] 12.8/31

But using std::move() prevents the return expression from being the name of the object you're returning. Instead the expression is more complicated and the language is no longer allowed to give it special handling.

The reason just naming the object is not worse than using std::move() is because there's another rule that says an expression can already be treated as an rvalue without needing std::move().

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.

Solution 2

Answering the question, sort of: return a string. Don't move anything, but rather use (rely on) RVO:

std::string func()
{
    std::string rv;
    /* ... */
    return rv;
}

This is how it generally should be done. You can't return an (r-value or not) reference to a temporary.

Solution 3

No need to say return std::move(str); if str is a local variable: If the variable satisfies the criteria for return-value optimisation, then in a return statement the variable will bind to an rvalue reference.

Also, beware that you should probably not return a reference to a local variable, neither lvalue nor rvalue reference.

All told, you should have:

int foo() { int x; /*...*/ return x; }
std::string bar() { std::string str; /*...*/ return str; }
Share:
31,422

Related videos on Youtube

EddieV223
Author by

EddieV223

Updated on July 09, 2022

Comments

  • EddieV223
    EddieV223 6 months

    Possible Duplicate:
    C++11 rvalues and move semantics confusion

    What I think is correct is

    std::string GetLine()
    {
    std::string str;
    std::getline(std::cin, str);
    return std::move(str);
    }
    

    But at this link http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html ( check the header part Returning an explicit rvalue-reference from a function)

    which is #1 google search hit for move semantics shows a similar function signature as

    int&& GetInt()
    {
    int x = 0;
    // code here
    return std::move(x);
    }
    

    From what I read at other places && means rvalue reference so in this case its returning a reference to an object that doesn't exist.

    So which is it?

    (Yes I know moving an int has no real benifit but the question is whether to use the return type of std::string or std::string&& in the first function. And if that is how it should be done for all types.)

    • eq-
      eq- over 10 years
      Are you sure you want to return an rvalue reference? Really?
    • Xeo
      Xeo over 10 years
      Just return str; with std::string GetLine()
    • EddieV223
      EddieV223 over 10 years
      I am wanting to explicitly use move semantics. I am wanting to know the syntax of it because it will be used for other types that I may write as well.
    • Alex F
      Alex F over 10 years
      Clent code: std::string s = GetLine() - value returned by GetLine is already rvalue, you don't need to "help" the compiler to understand this.
    • Bo Persson
      Bo Persson over 10 years
      Returning references to temporaries is just wrong, lvalue or rvalue references doesn't matter.
    • peterchen
      peterchen almost 7 years
      Note that the GetInt() example you have linked returns a rvalue reference to a global variable and decides: Now on to the question of whether you want to do this. The answer is: probably not. -- the article you linked just uses this to demonstrate a particular behavior.
  • celtschk
    celtschk over 10 years
    Remove "probably". You should not return a reference to a local variable. It is always undefined behaviour, plain and simple.
  • Kerrek SB
    Kerrek SB over 10 years
    @celtschk: Yes, indeed :-) Imagine this, though: T & f(T & a) { T & b = a; return b; } Good or bad?
  • celtschk
    celtschk over 10 years
    That doesn't return a reference to a local variable. It returns a reference not to b but to what b refers to. Which in turn is what a refers to. Which clearly is defined outside the function, and therefore cannot be a local variable of the function.
  • Kerrek SB
    Kerrek SB over 10 years
    @celtschk: OK, true. To be sure, b is indeed a local variable, but the return statement does not return a reference to it, but rather to whatever a refers to.
  • celtschk
    celtschk over 10 years
    Yes, b is definitely local. But there's no way you could return (or even obtain) a reference to it. Every use of the symbol refers to the object it is bound to.
  • EddieV223
    EddieV223 over 10 years
    Could you go into details about how std::move() could be worse?
  • mloskot
    mloskot over 8 years
    Are you using RVO and copy elision interchangeably?
  • bames53
    bames53 over 8 years
    @mloskot RVO is copy elision on return statements. So I'm using RVO to refer to a specific kind of copy elision.
  • mloskot
    mloskot over 8 years
    @bames53 I was imprecise in my comment, I meant to ask about RVO vs copy-construction elision (by move-construction). IOW, RVO as compiler optimisation versus copy/move-construction as in C++ language rules, which are two very different situations of eliding a copy.
  • bames53
    bames53 over 8 years
    @mloskot Right, copy-elision/RVO (n3337 § 12.8/31) is distinct from the special rules that require moves instead of copies in certain circumstances (n3337 § 12.8/32). I'm using RVO to refer only to the former.