Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the sizes passed into A::operator new() always equal to sizeof(A)?

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.

like image 473
xmllmx Avatar asked Aug 27 '13 03:08

xmllmx


1 Answers

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.

like image 181
Mats Petersson Avatar answered Oct 10 '22 09:10

Mats Petersson