我想知道在函數中傳遞r值時的C++行爲。函數中的r值參數
看看這個簡單的代碼:
#include <string>
void foo(std::string&& str) {
// Accept a rvalue of str
}
void bar(std::string&& str) {
// foo(str); // Does not compile. Compiler says cannot bind lvalue into rvalue.
foo(std::move(str)); // It feels like a re-casting into a r-value?
}
int main(int argc, char *argv[]) {
bar(std::string("c++_rvalue"));
return 0;
}
我知道當我在裏面bar
功能我需要使用move
功能,以調用foo
功能。我現在的問題是爲什麼?
當我的bar
函數內部的變量str
應該已經是一個r值,但是編譯器就像是一個升價值。
有人可以引用一些關於這種行爲的標準嗎? 謝謝!
命名對象始終是左值。這就是爲什麼你需要'移動'。 –