Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a modifiable rvalue and a const rvalue?

Tags:

c++

rvalue

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?

like image 775
Big Boss Avatar asked Mar 25 '17 16:03

Big Boss


1 Answers

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.

}
like image 92
Santiago Varela Avatar answered Nov 07 '22 06:11

Santiago Varela