问题
string three() { return “kittens”; }
const string four() { return “are an essential part of a healthy diet”; }
According to this article, the first line is a modifiable rvalue while the second is a const rvalue. Can anyone explain what this means?
回答1:
The return values of your function are copied using std::string's copy constructor. You can see that if you step through your program execution with a debugger.
As the conments say, it's quite self explantory. The first value will be editable when you return it. The second value will be read-only. It is a constant value.
For example:
int main() {
std::cout << three().insert(0, "All ") << std::endl; // Output: All kittens.
std::cout << four().insert(0, "women ") << std::endl; // Output: This does not compile as four() returns a const std::string value. You would expect the output to be "women are an essential part of a healthy diet”. This will work if you remove the const preceding the four function.
}
回答2:
An rvalue is the one which can be written at the write side of an assignment operator. A Modifiable Rvalue is the one (as it is visible from name) whose value can be changed at any time during execution. While, on the other hand, const Rvalue is a constant which cannot be changed during Program execution.
来源:https://stackoverflow.com/questions/43019243/what-is-the-difference-between-a-modifiable-rvalue-and-a-const-rvalue