string three() { return "kittens"; }
const string four() { return "are an essential part of a healthy diet"; }
根据这篇文章,第一行是可修改rvalue,而第二行是const rvalue。有人能解释一下这是什么意思吗?
您的函数的返回值是使用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.
}
four().begin(), four.end()
吗?那不是指向不同的 std::string
的迭代器吗? - Zereges
three()[0] = 'K'
,而使用第二个函数无法执行此类操作。 - Some programmer dude