What is the difference between a mutable r value and a const value?

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 mutable rvalue and the second is an rvalue constant. Can anyone explain what this means?


source to share

2 answers

The return values ​​of your function are copied using the std :: string copy constructor. You can see that if you execute your program using the debugger.

As the agreement says, it is quite a self-explorer. The first value will be editable when you return it. The second value will be read-only. This is a constant.

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.





rvalue is one that can be written on the write side of an assignment operator. A modifiable Rvalue is one (as the name suggests) whose value can be changed at any time during execution. A const Rvalue , on the other hand, is a constant that cannot be changed at runtime.



All Articles