디버깅을 위해 새 연산자와 삭제 연산자를 전역으로 바꿨고 이상한 동작이 발생했습니다. 삭제를 호출하면 C++에서 데이터를 해제하지 않습니다. 오류와C++은 새 연산자 및 삭제 연산자를 재정의 할 때 데이터를 해제하지 않습니다.
최소 코드 :
#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):
가
시작[+]는
만든 B에게
[+]를 만든 003e1a50 (12)
003e8630 (4)
가
완료
Allocs를 파괴 파괴 B
삭제합니다 : 2
2 allocations remaining! WHY???
EDIT1을 : 나는 -std = C++ 98을 사용하는 경우 또는 -std = C++ 11 플래그를 사용하면 오류가 사라지고 플래그 -std = C++ 14 및 -std = C++ 1z가 er 너.
'운영자 삭제'가 호출되지 않는 것 같습니다. –
나는 그것을 재현 할 수 없다. http://coliru.stacked-crooked.com/a/69ceb5d26a07b48f – Amadeus
'A * a = (B *) (new B);'왜 여기 던지니? –