可修改的右值和常量右值有什么区别?

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

本文关键字:什么 区别 修改 常量      更新时间:2023-10-16
string three() { return "kittens"; }
const string four() { return "are an essential part of a healthy diet"; }

根据这篇文章,第一行是可修改的右值,而第二行是常量右值。谁能解释一下这意味着什么?

函数的返回值是使用 std::string 的复制构造函数复制的。如果使用调试器单步执行程序,则可以看到这一点。

正如康门特所说,这是相当自我的。 返回第一个值时,它将是可编辑的。第二个值将是只读的。它是一个常量值。

例如:

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.
}

右值是可以在赋值运算符的写入端编写的值。可修改的右值是可在执行期间随时更改其值的右值(从名称中可见)。另一方面,常量右值是一个常量,在程序执行期间无法更改。