覆盖new和delete运算符时,C ++不会释放数据

时间:2017-11-08 23:16:25

标签: c++ malloc override operator-keyword free

我全局替换了new和delete运算符进行调试,我得到了奇怪的行为,看起来C ++在调用delete时没有释放数据。

带错误的最小代码:

#include "stdlib.h"
#include "stdio.h"

// Classes
class A
{
    int i;
public:
    A() { printf("Created A\n"); }
    virtual ~A() { printf("Destroyed A\n"); }
};
class B : public A
{
    int j;
public:
    B() { printf("Created B\n"); }
    ~B() { printf("Destroyed B\n"); }
};

unsigned int num_allocs = 0;
// Custom new/delete
void* operator new(size_t size)
{
    void* p = malloc(size);
    printf("[+] %p (%u)\n", p, size);
    num_allocs += 1;
    return p;
}
void operator delete(void* p)
{
    printf("[-] %p\n", p);
    num_allocs -= 1;
    free(p);
}

struct Z
{
    int k;
};

int main()
{
    printf("Started\n");
    A* a = (B*)(new B);
    Z* z = new Z;
    printf("Will delete\n");
    delete a;
    delete z;
    printf("Finished\n");
    printf("Allocs: %u\n", num_allocs);
    return 0;
}
  

输出(在Windows上使用MSYS2 + MinGW32进行编译):

开始

[+] 003e1a50(12)

创建A

创建B

[+] 003e8630(4)

将删除

被摧毁的B

摧毁了A

成品

Allocs:2

  

剩下2个分配! WHY ???

Edit1:当我使用-std = c ++ 98或-std = c ++ 11标志时,错误消失,标志-std = c ++ 14和-std = c ++ 1z重现错误。

1 个答案:

答案 0 :(得分:0)

它正在调用另一个delete函数。您应该提供

的定义
void operator delete(void* ptr, std::size_t size);

使用C ++ 17时,delete函数也应为noexcept