繁体   English   中英

这会导致c ++中的内存泄漏吗?

[英]Will this cause a memory leak in c++?

int* alloc()
{
    int* tmp = new int;
    return tmp;
}

int main()
{
    int* ptr = alloc();
    ......
    ......
    delete ptr;
    return 0;
}
  1. 在这里我没有释放tmp但是ptr被明确释放。 由于ptr和tmp指向相同的位置,tmp是否也会被释放?

  2. 如果不是那么指针tmp会发生什么? 它会导致内存泄漏吗?

不,这不会导致内存泄漏。 内存泄漏是已分配但未返回的缓冲区 (内存块)(当它们将不再使用时)。 在你的alloc()函数中, tmp不是一个缓冲区......它是一个变量,在调用new ,它保存缓冲区的地址 您的函数返回此地址,在main() ,该地址存储在ptr变量中。 当你再打delete ptr ,你是释放缓冲区 ptr点,从而缓冲已被释放,也没有泄漏。

如果没有抛出未捕获的异常,您的程序将不会导致内存泄漏。

你可以做得更好,让它像这样100%防弹:

#include <memory>

std::unique_ptr<int> alloc()
{
    std::unique_ptr<int> tmp { new int };
    //... anything else you might want to do that might throw exceptions
    return tmp;
}

int main()
{
    std::unique_ptr<int> ptr = alloc();

    // other stuff that may or may not throw exceptions

    // even this will fail to cause a memory leak.
    alloc();
    alloc();
    alloc();

    auto another = alloc();

    // note that delete is unnecessary because of the wonderful magic of RAII
    return 0;
}

尽早养成这个习惯。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM