I have seen this quote from an original article:
When we run sorted on an rvalue, it is safe to sort the data member directly. The object is an rvalue, which means it has no other users, so we can change the object itself. When we run sorted on a const rvalue or on an lvalue, we can’t change this object, so we copy data before sorting it
It said that a rvalue (temporary) can sort itself because it has no user. An lvalue cannot sort itself (sort a copy of it) because it maybe has users.
What is a user of lvalue? And what's the background?
Here is some code exemplifying the situation.
#include <vector>
#include <algorithm>
using namespace std;
class Foo {
public:
Foo() { std::cout << "default construct" << std::endl;}
Foo(const Foo &f) : data(f.data) {std::cout << "copy construct" << std::endl;}
Foo sort() &&;
Foo sort() const &;
private:
vector<int> data;
};
Foo Foo::sort() && {
std::cout << "rvalue sort" << std::endl;
std::sort(data.begin(), data.end());
return *this;
}
Foo Foo::sort() const & {
std::cout << "lvalue sort" << std::endl;
return Foo(*this).sort();
}