C++ 这些是否构成内存泄漏?

标签 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;
}

请注意,我只是在创建和使用此处显示的复制函数后才发现有关复制构造函数的信息。如果我要重做项目,我会改用复制构造函数。现在,当我使用这些函数时,我确保对我正在使用的任何变量调用“删除”。例如:

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/

相关文章:

c++ - C++ 新手,取消引用 vector 的一部分时程序没有响应?

c++ - 如何捕获 printf 的输出?

c - 我的堆栈实现中的数据泄漏

c# - 线程阻止所有者的垃圾收集

c++ - Visual Leak Detector 不适用于 VS2012 中的单元测试

c++ - Visual Leak Detector 报告一个 int* 有 40 个字节泄漏

c++ - 有 C++ 惰性指针吗?

c++ - 我可以列出核心转储中的所有 VTable 指针吗?

wpf - 使用WinDbg分析WPF应用程序中OutOfMemoryException的根本原因

c++ - CComPtr 内存泄漏