gpt4 book ai didi

c++ - 为什么不调用 std::string 移动构造函数?

转载 作者:可可西里 更新时间:2023-11-01 18:28:03 24 4
gpt4 key购买 nike

我有这个例子:

#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(str_) 替换为 str(std::move(str_)) 我会得到以下输出:

$ ./a.out
1. there: 1234567890
2. there:
3. there: 1234567890

这表明现在使用了 std::string 移动构造函数,但为什么在我的第一个示例中没有调用 std::string(std::string &&)

最佳答案

你应该这样做

public:
Test(std::string &&str_) :
str(std::move(str_))
{}

str_ 确实有一个名称,是一个命名对象,因此它不会作为右值引用传递给任何函数。

标准委员会做出的设计选择阻止它被视为右值,因此您不会无意中修改它。特别是:str_ do 的类型是对 string 的左值引用,但 str_ 不被视为右值,因为它是命名对象。

您必须通过添加对 std::move 的调用来表明您的意图。这样做你声明你希望 str_ 是一个右值并且你知道这个选择的所有后果。

关于c++ - 为什么不调用 std::string 移动构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33473386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com