I wrote some code to trace memory with an overridden new and delete operator:
#include <iostream>
#include <mutex>
std::mutex mtx;
auto operator new(size_t size) -> void* {
{
std::lock_guard<std::mutex> lock(mtx);
// std::cout << "Allocating " << size << " bytes\n";
printf("Allocating %zu bytes\n", size);
}
return malloc(size);
}
auto operator delete(void* p, size_t size) -> void {
{
std::lock_guard<std::mutex> lock(mtx);
// std::cout << "Freeing " << size << " bytes\n";
printf("Freeing %zu bytes\n", size);
}
free(p);
}
class Object {
public:
Object() = default;
~Object() = default;
private:
int a_;
int b_;
};
auto main(int argc, char** argv) -> int {
{
auto* object = new Object();
delete object;
}
return 0;
}
If I compile with Visual Studio Build Tools 2019 Release - amd64 everything is ok and it prints:
Allocating 8 bytes
Freeing 8 bytes
But when I compile with Clang 10.0.0 for MSVC with Visual Studio Build Tools 2019 Release (amd64) then delete is not called:
Allocating 8 bytes
Why clang has this behaviour?
This is the answer if anyone needs it. As @Eljay said in the comment, you need to override two versions the the
deleteoperator