When I run this code sample in GCC and Clang
struct S
{
int a;
void *operator new(size_t s)
{
std::cout << "new " << s << std::endl;
return ::operator new(s);
}
void operator delete(void *p, size_t s) noexcept
{
std::cout << "delete " << s << std::endl;
::operator delete(p);
}
void operator delete(void *p) noexcept
{
std::cout << "delete " << "none" << std::endl;
::operator delete(p);
}
};
int main()
{
S *p = new S;
delete p;
}
I get the following output from both GCC and Clang
new 4
delete none
which means that the compilers selected the "sizeless" version of operator delete
.
However, if I try something similar with globally replaced operator new
and operator delete
functions
struct S
{
int a;
};
void *operator new(size_t s)
{
std::cout << "new " << s << std::endl;
return std::malloc(s);
}
void operator delete(void *p, size_t s) noexcept
{
std::cout << "delete " << s << std::endl;
std::free(p);
}
void operator delete(void *p) noexcept
{
std::cout << "delete " << "none" << std::endl;
std::free(p);
}
int main()
{
S *p = new S;
delete p;
}
From GCC I get
new 4
delete 4
and from Clang I get
new 4
delete none
I know that "sized" version of in-class operator delete
has been present in C++ since C++98, but looking through C++98 I don't seem to be able to find a definitive answer to the question of what version of operator delete
should be selected in the first example. Is it even specified?
And what about C++14 and its "sized" version of global operator delete
in the second example? Does the language say which version should be selected?
operator delete[]
? – Sakmar