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?
+3
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.
}
+3
source to share