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

寵の児 提交于 2019-12-10 13:39:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!