gpt4 book ai didi

c++ - 防御性地将 std::move 应用于普通可复制类型是否不可取?

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:25 25 4
gpt4 key购买 nike

假设我们有一个简单可复制的类型:

struct Trivial
{
float A{};
int B{};
}

构造并存储在 std::vector 中:

class ClientCode
{
std::vector<Trivial> storage{};
...

void some_function()
{
...
Trivial t{};
fill_trivial_from_some_api(t, other_args);

storage.push_back(std::move(t)); // Redundant std::move.
...
}
}

通常,这是一个毫无意义的操作,因为无论如何都会复制对象。

但是,保留 std::move 调用的一个优点是,如果 Trivial 类型将更改为不再是普通可复制的,则客户端代码将不是默默地执行额外的复制操作,而是更合适的移动。 (这种情况在我的场景中很有可能,其中 trivial 类型用于管理外部资源。)

所以我的问题是应用冗余 std::move 是否有任何技术缺点?

最佳答案

However, an advantage of keeping the std::move call is that if the Trivial type would be changed to no longer be trivially-copyable, the client code will not silently perform an extra copy operation, but a more appropriate move.

这是正确的,您应该考虑一下。


So my question is whether there any technical downsides to applying the redundant std::move?

取决于移动对象的消费位置。在 push_back 的情况下,一切都很好,因为 push_backconst T&T&& 重载,它们的行为很直观.

想象另一个具有 T&& 重载的函数,它具有与 const T& 完全不同的行为:代码的语义将随着 std::move.

关于c++ - 防御性地将 std::move 应用于普通可复制类型是否不可取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49241201/

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