gpt4 book ai didi

c++ - 我是否正确使用 move 语义?会有什么好处?

转载 作者:行者123 更新时间:2023-11-30 05:43:16 26 4
gpt4 key购买 nike

我想知道我是否正确使用了 move 语义:

class Vertex{
protected:
Common::Point3D position;
Common::Point3D normal;
Common::Point2D uv;
Common::Point2D tangent;
public:
Vertex(Common::Point3D &&position, Common::Point3D &&normal, Common::Point2D &&uv, Common::Point2D &&tangent)
: position(std::move(position)), normal(std::move(normal)), uv(std::move(uv)), tangent(std::move(tangent)){}
};

我将通过 move 实现什么? 用于比较的代码(我也可以使用 const &):

class Vertex{
protected:
Common::Point3D position;
Common::Point3D normal;
Common::Point2D uv;
Common::Point2D tangent;
public:
Vertex(Common::Point3D position, Common::Point3D normal, Common::Point2D uv, Common::Point2D tangent)
: position(position), normal(normal), uv(uv), tangent(tangent){}
};

将阻止多少次复制,其中哪些会发生?

我想使用这样的代码:

Vertex * vertices = new Vertex[10000];
vertices[0] = Vertex(Common::Point3D(1,2,3), Common::Point3D(4,5,6)...);
vertices[1] = ...

我可以进一步优化它吗?

最佳答案

I wonder if I use the move semantic correctly:

通过仅接受右值引用,您限制了将左值传递给此构造函数。您可能会很快发现您不能像您期望的那样使用它。如果您按值接受类型...

Vertex(Common::Point3D position, Common::Point3D normal, Common::Point2D uv, Common::Point2D tangent)
: position{std::move(position)}
, normal{std::move(normal)}
, uv{std::move(uv)}
, tangent{std::move(tangent)}
{}

...您允许类的用户 move 复制到构造函数变量中,然后您总是 move 到您的成员变量。这意味着您将始终导致 1 个拷贝和 1 个 move 或 2 个 move ,具体取决于 ctor 的调用方式。或者,您可以使用 const& 并且无论如何始终只生成 1 个拷贝。如果您想成为无可否认的最快的,您将对 &&const& 的每个组合进行重载,但这样的代码太多了。

What will I achieve here with move?

假设 Point3D 仅包含 3 个整数/ float / double ,您不会获得任何结果。基本类型不会从 move 中获得任何东西,它与拷贝相同。

move 的最大好处通常是您可以“窃取”动态分配的内存。想一想 vector,它动态分配一个数组并保存指向它的指针。当您 move 它时,它可以简单地将指针复制到新对象并清空原始指针。当您复制它时,它会在新对象中分配新内存并将数组(可能逐个元素)复制到新数组中。巨大的成本差异:与仅复制指针相比,分配和复制数组元素。

结论:对于您的类型,通过 const& 传递可能是最快的方法。

关于c++ - 我是否正确使用 move 语义?会有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30313273/

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