【发布时间】:2023-04-03 06:25:01
【问题描述】:
我想知道我是否正确使用了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] = ...
我可以进一步优化它吗?
【问题讨论】:
-
有没有好处就看
Point2D和Point3D的内容了,从他们的名字来看,搬家很可能没有好处。 -
Point3D只是class Point3D{float x, y,z;}与一些自定义set和get方法。 -
然后复制这些内容或在适当的地方通过引用传递。这里没有什么可以加速的。
-
@PolGraphic 所以不。搬家对复制没有好处。但是这两个代码 sn-ps 之间的区别在于,第一个构造函数只接受右值,而第二个构造函数同时接受左值和右值。
-
这就是我的想法。对于基本类型,移动和复制是相同的,所以这个类根本不会从移动中受益。为了约定,我可能会将构造函数定义为
Vertex(Common::Point3D position, ...) : position(std::move(position)), ... {}与您的第一个定义不同,这个也将接受左值(如果没关系,那么您的第一个定义就可以了)
标签: c++ c++11 move move-semantics