struct A final
{
int a;
void* operator new(size_t size)
{
//
// Is size always equal to sizeof(A) here?
//
return ::operator new(size);
}
void operator delete(void* ptr)
{
::operator delete(ptr);
}
};
int main()
{
for (auto i = 0; i < 100; i++)
{
delete new A;
}
}
My question is also embedded in the code.
Does the C++ standard guarantee the sizes passed into A::operator new() are always the same?
Update: Here, just consider A is a final class only.
Quote from the C++11 standard, section 5.3.4 point 10:
A new-expression passes the amount of space requested to the allocation function as the first argument of type std::size_t. That argument shall be no less than the size of the object being created; it may be greater than the size of the object being created only if the object is an array.
So, yes, it's guaranteed to be the same as the size of the object. Note however that different compilers or different compiler options may alter the actual size of a particular object at compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With