我有这样的例子:为什么不调用std :: string移动构造函数?
#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。虽然移动后there
字符串将保持有效但不确定的状态,但如果调用std :: string移动构造函数,此实现似乎会移动(而不是复制)该字符串。
如果我更换initalizer str(str_)
与str(std::move(str_))
我得到这样的输出:
$ ./a.out
1. there: 1234567890
2. there:
3. there: 1234567890
此建议的std :: string移动构造函数现在使用的,但为什么在我的第一个例子是不是std::string(std::string &&)
调用?