c++ - 可修改右值和常量右值有什么区别?

标签 c++ rvalue

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/

相关文章:

C++ : Association, 聚合和组合

c++ - OpenCV 显示没有来自 Macbook 网络摄像头的视频

c++ - 将 bool 值从参数复制到全局值-比较编译器输出

c++ - 传递 const int* 和 int* 时调用不同版本的重载函数 (const int* const&/&&)

C++ 箭头类型产生左值

c++ - 在 C++ 中自动更新新结构中的相关值

c++ - 寻找一个 constexpr ceil 函数

c++ - 将参数作为 const & 或 && 传递

C++0x const RValue 引用作为函数参数

c++ - 右值不适用于引用