string three() { return "kittens"; }
const string four() { return "are an essential part of a healthy diet"; }
根据 this文章中,第一行是一个可修改的右值,而第二行是一个常量右值。谁能解释一下这是什么意思?
最佳答案
函数的返回值是使用 std::string 的复制构造函数复制的。如果您使用调试器逐步执行程序,您会看到这一点。
正如评论所说,这完全是 self 解释。当您返回第一个值时,它是可编辑的。第二个值将是只读的。它是一个常数值。
例如:
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.
}
关于c++ - 可修改右值和常量右值有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43019243/