可修改的右值和常量右值有什么区别?
What is the difference between a modifiable rvalue and a const rvalue?
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.
}
右值是可以在赋值运算符的写入端编写的值。可修改的右值是可在执行期间随时更改其值的右值(从名称中可见)。另一方面,常量右值是一个常量,在程序执行期间无法更改。
相关文章:
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- Qt:remove() 和 rmdir() 有什么区别
- 这 4 个 lambda 表达式之间有什么区别?
- 将向量作为类>(值)<向量启动和向量<类>[值]有什么区别
- typedef 枚举和枚举类有什么区别?
- &C::c 和 &(C::c) 有什么区别?
- ascii 和 unicode 在处理级别有什么区别吗?
- C 中的常量限定符和 C++ 中的常量限定符有什么区别?
- "ABC" 和 "ABC" ) 在C++中有什么区别?
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 引用捕获和在 lambda 中通过引用发送参数有什么区别 (C++)
- 两种访问I2C总线的方法有什么区别?
- 两种模板示例有什么区别?
- 这两种C++语法之间有什么区别?
- lua 5.0.2 模块和 5.3.5 有什么区别?
- C++中"typedef"、"using"、"namespace"和"using namespace"有什么区别?
- std::enable_if 和 std::enable_if_t 有什么区别?