我一直在研究一个简单的光线追踪器,但遇到内存不足的问题。我为 visual studio 下载了 Visual Leak Detector,它告诉我以下函数导致内存泄漏。但是,我不确定为什么这些会被视为泄漏:
Point* Point::copy() {
Point* result = new Point(x, y, z);
return result;
}
Point* Point::crossProduct(Point* other) {
double crossX = y*(*other).getZ() - z*(*other).getY();
double crossY = z*(*other).getX() - x*(*other).getZ();
double crossZ = x*(*other).getY() - y*(*other).getX();
Point* cross = new Point(crossX, crossY, crossZ);
return cross;
}
请注意,我只是在创建和使用此处显示的复制函数后才发现有关复制构造函数的信息。如果我要重做项目,我会改用复制构造函数。现在,当我使用这些函数时,我确保对我正在使用的任何变量调用“删除”。例如:
Point* n = AB.crossProduct(&AC);
...
delete n;
我认为这应该处理任何内存泄漏是错误的吗? Visual Leak Detector 是否只是因为泄漏在单独的文件中而无法识别泄漏已得到处理?
最佳答案
为什么不按值返回,而按常量引用传递呢?
Point Point::copy()
{
return Point(x, y, z);
}
Point Point::crossProduct(const Point& other)
{
double crossX = y * other.getZ() - z * other.getY();
double crossY = z * other.getX() - x * other.getZ();
double crossZ = x * other.getY() - y * other.getX();
return Point(crossX, crossY, crossZ);
}
当然,您的 copy
函数只是一个穷人的复制构造函数/赋值运算符,所以请改用它们:
Point::Point(const Point& other)
: x(other.x)
, y(other.y)
, z(other.z)
{
}
Point& Point::operator=(const Point& other)
{
x = other.x;
y = other.y;
z = other.z;
return *this;
}
关于C++ 这些是否构成内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25986127/