L
L
lemon_spb2016-08-09 21:38:47
C++ / C#
lemon_spb, 2016-08-09 21:38:47

Overriding operator delete [] for a class. Glitch?

Good afternoon, ladies and gentlemen.
It was required to replace a heap with "custom" in the project.
I'm reading on cppreference about the delete [] operator . There is this code:

#include <iostream>
// sized class-specific deallocation functions
struct X {
    static void operator delete(void* ptr, std::size_t sz)
    {
        std::cout << "custom delete for size " << sz << '\n';
        ::operator delete(ptr);
    }
    static void operator delete[](void* ptr, std::size_t sz)
    {
        std::cout << "custom delete for size " << sz << '\n';
        ::operator delete(ptr);
    }
};
int main() {
     X* p1 = new X;
     delete p1;
     X* p2 = new X[10];
     delete[] p2;
}

Possible output:
custom delete for size 1
custom delete for size 18

Under ubuntu with GCC this code works. All OK. Here, for example, on ideone.com:
https://ideone.com/KxXjuG
And here is some nonsense in the Studio:
custom delete for size 1
custom delete for size 1

Online studio compiler with the same example:
rextester.com/QUKDSZ7278
How to be? Heap size needs to be measured. But if delete[] gets some nonsense instead of size, then the measurements are meaningless. Where did I get stuck?
PS: at the same time, operator new [], if you add it, gets the correct size of the array + sizeof of the pointer.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MiiNiPaa, 2016-08-09
@limon_spb

This is a bug in Visual Studio . You can get around it by declaring a destructor for the class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question