0

如果没有,下面的代码会产生内存泄漏。可以肯定地说微软错过了这一点吗?

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

template <typename T>
class class_leak
{
private:
    T *p_;

public:
    class_leak(T *p) :
        p_(p)
    {}

    ~class_leak()
    {
        delete p_;
    }
};

int main(int /*argc*/, char * /*argv*/[]) {
    int *x = new int(10);
    class_leak<int> cl(x);
    _CrtDumpMemoryLeaks();
}

产品:

Detected memory leaks!
Dumping objects ->
{56} normal block at 0x000D1540, 4 bytes long.
 Data: <    > 0A 00 00 00 
Object dump complete.
The program '[4584] unique_ptr.exe: Native' has exited with code 0 (0x0).
4

1 回答 1

2

泄漏检测确实有点简单。它只检查当前的分配平衡,而不是仍然可以释放的内存。不需要 RAII 甚至 C++ 来证明:

int *p = malloc(10);
_CrtDumpMemoryLeaks();
free(p);
于 2013-08-12T06:47:52.840 回答