【发布时间】:2014-01-15 08:38:45
【问题描述】:
我对通过函数调用传递右值有点困惑,请参阅下面的代码:
#include <string>
#include <iostream>
void func(std::string & s, char a) {
std::cout << "here1" << std::endl;
// ...
}
void func(std::string && s, char a) {
std::cout << "here2" << std::endl;
// ...
}
void foo(std::string && s) {
func(s, ':');
}
int main(int agrc, char *argv[])
{
std::string s = "a:b:c:d";
func(std::move(s), ':'); // print here2
char s2[8] = "a:b:c:d";
func(std::move(std::string(s2)), ':'); // print here2
foo(std::move(s2)); // print here1, why?
return 0;
}
g++-4.7 demo.cpp -std=c++11
为什么最后一个案例(使用foo)打印here1?
在我看来,函数内部foo,s是一个右值,所以它会打印here2。
更新:
foo中的s是左值,但是不需要写foo的重载版本:
void foo(std::string & s) {
func(s, ':');
}
因为编译器可以知道输入参数s是右值还是左值,但是为什么编译器在右值情况下不自动移动s?
【问题讨论】:
-
它不会因为同样的原因被自动移动,它是一个左值。左值仅在非常有限的上下文中自动移动,例如函数的 return 语句,您可以确信它的生命周期即将结束。
标签: c++ c++11 move rvalue-reference rvalue