C++ 在重写 new 和 delete 运算符时不释放数据
C++ don't free data when overriding new and delete operators
我在全局范围内替换了 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;
}
Output (Compiling with MSYS2 + MinGW32 on Windows):
开始
[+] 003e1a50 (12)
创建了一个
创建 B
[+] 003e8630 (4)
将删除
摧毁B
摧毁A
已完成
分配:2
2 allocations remaining! WHY???
Edit1:当我使用 -std=c++98 或 -std=c++11 标志时,错误消失,标志 -std=c++14 和 -std=c++1z 重现错误。
它正在调用另一个 delete
函数。您应该为
提供定义
void operator delete(void* ptr, std::size_t size);
当使用 C++17 时,delete
函数也应该是 noexcept
。
我在全局范围内替换了 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;
}
Output (Compiling with MSYS2 + MinGW32 on Windows):
开始
[+] 003e1a50 (12)
创建了一个
创建 B
[+] 003e8630 (4)
将删除
摧毁B
摧毁A
已完成
分配:2
2 allocations remaining! WHY???
Edit1:当我使用 -std=c++98 或 -std=c++11 标志时,错误消失,标志 -std=c++14 和 -std=c++1z 重现错误。
它正在调用另一个 delete
函数。您应该为
void operator delete(void* ptr, std::size_t size);
当使用 C++17 时,delete
函数也应该是 noexcept
。