0

How to comprephend these ways(including not making variables’ scopes needlessly large, writing short functions that return values, returning local variables) could eliminate most need for explicit std::move?

Could anybody make it clear by some simple examples?I am a novice in C++.I would be grateful for any hint on this question. For your convenience, I post all the quotes below.

Moving is done implicitly when the source is an rvalue (e.g., value in a return treatment or a function result), so don’t pointlessly complicate code in those cases by writing move explicitly. Instead, write short functions that return values, and both the function’s return and the caller’s accepting of the return will be optimized naturally. In general, following the guidelines in this document (including not making variables’ scopes needlessly large, writing short functions that return values, returning local variables) help eliminate most need for explicit std::move.

sunshilong369
  • 646
  • 1
  • 5
  • 17
  • 2
    Keep in mind that `std::move` is just a type cast and doesn't actually do anything; it just creates the opportunity for "moving" (which doesn't physically move anything) if it didn't already exist. – molbdnilo May 27 '20 at 13:45
  • Returning by value from a function functionally casts to rvalue. You don't need to write `std::move(my_function())` when `my_function` returns by value. It's the same as `my_function()`. I *think* the advice in the quote is to use these kinds of functions more to reduce the number of `std::move`s. But I'm not sure that is good advice. If you go out of your way to write a function just to produce an rvalue, just use `std::move` instead and make everything clear to future readers. – François Andrieux May 27 '20 at 13:51
  • 4
    Does this answer your question? [What are copy elision and return value optimization?](https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) – Richard Critten May 27 '20 at 14:00
  • First of all, Thank you very much.The documentation forementioned is very useful indeed.But,i think it could not answer my question because i want to know why the several ways could eliminate most need for explicit `std::move`. – sunshilong369 May 27 '20 at 14:53

1 Answers1

1

By creating sub-functions, you might change

void consume(std::vector<int>&&);

void foo()
{
    std::vector<int> v;
    for (int i = 0; i != 10; ++i) {
        v.push_back(i);
    }
    consume(std::move(v));
}

by

void consume(std::vector<int>&&);

std::vector<int> make_vector()
{
    std::vector<int> v;

    for (int i = 0; i != 10; ++i) {
        v.push_back(i);
    }
    return v; // implicit move. or NRVO
}
void foo()
{
    consume(make_vector()); // no explicit move needed.
}

which also allow better reading.

Jarod42
  • 203,559
  • 14
  • 181
  • 302