I have this example:
#include <string>
#include <iostream>
class Test {
private:
std::string str;
public:
Test(std::string &&str_) :
str(str_)
{}
const std::string &GetStr()
{
return str;
}
};
int main(int argc, char *argv[])
{
std::string there("1234567890");
std::cout << "1. there: " << there << '\n';
Test t1(std::move(there));
std::cout << "2. there: " << there << '\n';
std::cout << "3. there: " << t1.GetStr() << '\n';
}
它会输出:
$ ./a.out
1. there: 1234567890
2. there: 1234567890
3. there: 1234567890
这是在Linux上使用gcc 5.1.1。当使用std::string的移动构造函数时,虽然there
字符串将保持有效但不确定的状态,但此实现似乎移动(而不是复制)字符串。
如果我将初始化器str(str_)
替换为str(std::move(str_))
,我会得到以下输出:
$ ./a.out
1. there: 1234567890
2. there:
3. there: 1234567890
这表明现在使用了std::string的移动构造函数,但为什么在我的第一个例子中没有调用std::string(std::string &&)?