简体   繁体   English

MSVC _Crt *宏在RAII代码中使用不安全

[英]MSVC _Crt* Macros Are not Safe to use in RAII Code

The code below produces a memory leak when there is none. 如果没有,下面的代码会产生内存泄漏。 Is it safe to say that Microsoft missed the mark on this one? 可以说微软错过了这个标记吗?

#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();
}

Prodcues: Prodcues:

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).

The leak detection is indeed a bit simplistic. 泄漏检测确实有点简单。 It checks just the current balance of allocations, not what memory can still be freed. 它只检查当前的分配余额,而不是仍然可以释放的内存。 Doesn't need RAII or even C++ to demonstrate that: 不需要RAII甚至C ++来证明:

int *p = malloc(10);
_CrtDumpMemoryLeaks();
free(p);

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

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