我有代码:
class Vector3D : public Vector{
protected:
Point3D * start;
Point3D * end;
public:
~Vector3D(){delete start; delete end;}
Vector3D(Point3D * start, Point3D * endOrLength, bool fromLength){
this->start = start;
if(fromLength){
this->end = new Vector3D(*start+*endOrLength); //the operator '+' is defined but I won't put it here,
//because it's not important now
}else
this->end = endOrLength;
}
Point3D * getStart(){return start;}
Point3D * getEnd(){return end;}
};
现在,我有代码:
Vector3D v(new Point3D(1,2,3), new Point3D(2,3,4), 0); //FIRST CREATION
Vector3D v(new Point3D(1,2,3), new Point3D(1,1,1), 1); //SECOND CREATION
第一次和第二次创建给了我相同的 Vector3D,但我认为它可能会产生内存泄漏。
是真的吗?以及如何解决?我想这样做并不优雅:
...
if(fromLength){
this->end = new Vector3D(*start+*endOrLength);
delete endOrLength;
}else
...
也许最好放 const Point3D &endOrLenght,我不知道有什么好方法?与 getStart/getEnd 相同 -它是否应该返回指针:
Point3D * getStart(){return start;}
或者只是变量:
Point3D getStart()(return *start)
?