【发布时间】:2012-07-02 11:41:18
【问题描述】:
我有代码:
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)
?
【问题讨论】:
标签: c++ function pointers reference parameters