gpt4 book ai didi

c++ - 为什么要使 move 的对象或右值无效?

转载 作者:行者123 更新时间:2023-12-05 04:25:27 30 4
gpt4 key购买 nike

<分区>

在此answer有一个 string 对象的 move 构造函数的示例实现:

    string(string&& that)   // string&& is an rvalue reference to a string
{
data = that.data;
that.data = nullptr;
}

除了这个玩具示例之外,我还看到很多地方都说

a moved object shall be in a valid but unspecified state.

例如 std::string 在被 move 后通常是一个空的。我的问题是为什么要费心去改变右值的状态?如果右值引用是对被调用者的提示“我们不再需要该对象,所以用它做任何你想做的事”,那么为什么要更改它并将其设置为 nullptr 或使字符串为空?如果来电者告诉我们我不再使用它,我们将无能为力。

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