C++ C++;类文件中的对象实例化
我正在制作一个带有向量类的模块/库,我希望它能够正确地完成C++ C++;类文件中的对象实例化,c++,class,memory-management,allocation,C++,Class,Memory Management,Allocation,我正在制作一个带有向量类的模块/库,我希望它能够正确地完成 class Vector3 { public: float x, y, z; public: Vector3(); Vector3(float a, float b, float c); float length(); void normalize(); Vector3* dotproduct(Vector3 *rhs); Vector3* crossproduct(Vector3
class Vector3 {
public:
float x, y, z;
public:
Vector3();
Vector3(float a, float b, float c);
float length();
void normalize();
Vector3* dotproduct(Vector3 *rhs);
Vector3* crossproduct(Vector3 *rhs);
Vector3* add(Vector3 *rhs);
Vector3* subtract(Vector3 *rhs);
};
我的疑问是,在一次操作后,我应该如何返回一个新的矢量3
目前,我正在每个操作中动态分配一个新的Vector3
,然后返回它
当我使用该操作时,我有:
Vector3*v=v2->叉积(v3)代码>
我是否应将我的操作更改为:
Vector3 Vector3::crossproduct(Vector3 *rhs){
float a = y * rhs->z - z * rhs->y;
float b = z * rhs->x - x * rhs->z;
float c = x * rhs->y - y * rhs->x;
Vector3 res(a, b, c);
return res ;
}
和使用:
vector3v=v2->叉积(v3)代码>
还是我最终会失去向量?
既然我想建立一个图书馆,那么什么才是正确的方法呢?
在堆栈或堆中分配?我实现以下操作:
Vector3 Vector3::crossproduct(const Vector3& rhs){
float a = y * rhs.z - z * rhs.y;
float b = z * rhs.x - x * rhs.z;
float c = x * rhs.y - y * rhs.x;
Vector3 res(a, b, c);
return res ;
}
要使用此运算符,只需使用以下语法:
Vector v1, v2;
auto product = v1.crossproduct(v2);
返回值很可能是通过复制省略优化的,因此您不必担心这一点。由于未修改rhs
,因此将其作为const ref&传递是最快的方法。使用&
运算符的主要区别是什么?引用限定符(&)几乎就像一个指针。唯一的区别是,您不能重新分配引用,它们必须始终进行初始化。构造函数Vector3 res(…)
将在堆栈上分配您的结果,这是您希望对小对象执行的操作。没有理由将其放在堆上,因为您必须关心释放,而且由于缓存未命中率较高,这也会降低性能。另外,您应该不惜一切代价避免使用原始指针。如果要处理堆内存,请使用std::unique_ptr
和std::shared_ptr
。如果你不这样做,你很可能会在你的程序内存泄漏。不要把向量堆。这样做没有意义,你只能失去宝贵的周期。是的,你应该这样做。不,你不会的。为什么要使用指针和动态分配?这在这里毫无用处。放在一边:命名add
和subtract
方法的正确方法是Vector3和操作符+=(const-Vector3和rhs)
和Vector3和操作符-=(const-Vector3和rhs)
,以及添加非成员Vector3操作符+(Vector3-lhs,const-Vector3和rhs)
和Vector3操作符-(Vector3 lhs、const Vector3和rhs)
附加:我希望dotproduct
返回一个float
(或类似的标量类型)修复了dotproduct
。不应该是Vector3和Vector3::operator+(const Vector3和rhs)
,因为我想像v=v2+v3
?