【发布时间】:2023-03-16 23:04:01
【问题描述】:
我有这个例子:
#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 移动构造函数,此实现似乎会移动(而不是复制)字符串。
如果我用str(std::move(str_)) 替换初始化器str(str_),我会得到这个输出:
$ ./a.out
1. there: 1234567890
2. there:
3. there: 1234567890
这表明现在使用了 std::string 移动构造函数,但为什么在我的第一个示例中没有调用 std::string(std::string &&) ?
【问题讨论】:
标签: c++