0 c++ memory-leaks visual-leak-detector
我一直在研究一个简单的光线跟踪器,我遇到了内存不足的问题.我为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;
}
Run Code Online (Sandbox Code Playgroud)
注意我在创建和使用此处显示的复制功能后才发现有关复制构造函数的信息.如果我要重做项目,我会使用复制构造函数.现在,当我使用这些函数时,我确保在我正在使用的任何变量上调用"delete".例如:
Point* n = AB.crossProduct(&AC);
...
delete n;
Run Code Online (Sandbox Code Playgroud)
我认为这应该处理任何内存泄漏我错了吗?Visual Leak Detector是否因为它在一个单独的文件中而无法识别泄漏?
为什么不按值返回,并通过const引用?
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);
}
Run Code Online (Sandbox Code Playgroud)
当然你的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;
}
Run Code Online (Sandbox Code Playgroud)