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

c++ - Difference between "return-by-rvalue-ref" & "return-by-value" when you return using std::move?

Considering the following code:

#include <iostream>
using namespace std;

struct I {
    I(I&& rv) { cout << "I::mvcotr" << endl; }
};

struct C {
    I i;
    I&& foo() { return move(i) };
    }
};

int main() {
    C c;
    I i = c.foo();
}

C contains I. And C::foo() allows you to move I out of C. What is the difference between the member function used above:

I&& foo() { return move(i) }; // return rvalue ref

and the following replacement member function:

I foo() { return move(i) }; // return by value

To me, they seem to do the same thing: I i = c.foo(); leads to a call to I::I(I&&);.

What consequences will there be that is not covered in this example?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Considerations aside on whether the program you wrote actually makes sense (moving from a data member is awkward - but OK, perhaps there are some use cases), in this case the two versions of that function end up doing the same thing.

As general practice, however, you should prefer returning by value, because in many cases it allows the compiler to perform copy elision and elide the calls to the move constructor of the returned type, as permitted by paragraph 12.8/31 of the C++11 Standard.

Copy elision allows the compiler to create the return value of the function directly in the object which should be initialized from the function's return value.

Therefore, as a general guideline, prefer returning by value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

56.8k users

...