I saw this question recently Is returning by rvalue reference more efficient? and also noticed the comments chain. I am following up on the comments chain for the answer there.
People seem to say that in the case below the return value should be by rvalue reference and not by value. (Is returning by rvalue reference more efficient? and Is there any case where a return of a RValue Reference (&&) is useful?) Given the following code
#include <iostream>
using namespace std;
class Something {
public:
Something() {
cout << "Something()" << endl;
}
Something(const Something&) {
cout << "Something(const Something&)" << endl;
}
Something(Something&&) {
cout << "Something(Something&&)" << endl;
}
};
class Maker {
public:
Something get_something() && {
return std::move(this->something);
}
const Something& get_something() & {
return this->something;
}
private:
Something something;
};
int main() {
auto maker = Maker{};
auto something_one = maker.get_something();
auto something_two = Maker{}.get_something();
return 0;
}
What is the difference between defining the first method in the class Maker
with an rvalue reference return type and a regular value? Running the code above gives me the following output as expected (the move happens in the function call and after the return the move is elided)
Something()
Something(const Something&)
Something()
Something(Something&&)
And when I change the code (i.e. the first method in the Maker
class) to return an rvalue reference I still get the same output. Why shouldn't I just return by value in that case?