Argument value for operator new [] in C ++

Consider the following code, which contains a class with overloads for new

and new[]

:

#include <iostream>


class my_class  {
public:
    my_class() {};
    my_class(const my_class& rhs) {};
    ~my_class() {};

//the constructor also as applicable.
    void * operator new(size_t sz); 
    void * operator new[](size_t sz);
    void operator delete(void * ptr);
    void operator delete[](void * ptr);
private:    
};

void * my_class::operator new(size_t sz)
{
    std::cout << "at operator new, sz is: " << sz << std::endl;
}

void * my_class::operator new[](size_t sz)
{
    std::cout << "at operator new[], sz is: " << sz << std::endl;
}

void my_class::operator delete(void * ptr)
{
    std::cout << "at operator delete, ptr is: " << ptr << std::endl;
}

void my_class::operator delete[](void * ptr)
{
    std::cout << "at operator delete[], ptr is: " << ptr << std::endl;
}

int main(int argc, char ** argv)
{
    my_class * ptr = new my_class;
    my_class * arr_ptr = new my_class[1];
    return 0;
}

      

By running this in terminal (Cygwin) I see:

at operator new, sz is: 1
at operator new[], sz is: 9

      

Why sz == 9

is it called operator new[]

? Who installs it? What does it depend on (eg page size?)?

+3


source to share


2 answers


The new expression, for example new my_class

, is more than a challenge operator new

; operator new

only allocates memory, and its parameter is the size of the memory that it should allocate.

The parameter sz

of operator new

is equal to 1, because it is the smallest possible instance; sizeof(my_class)

is equal to 1.



The sz

of parameter operator new[]

is 9 because that is how much memory new[]

-expression ( new my_class[1]

) takes to allocate an array of 1 instance of size 1.

"Extra" 8 is for keeping track of things like item count. The size of the "extra" memory is implementation dependent.

+2


source


runtime "sets" the value when the statement is invoked new

. There is an implicit one sizeof

. This is the same situation as when calling member functions that implicitly loop around the pointer to the current instance this

.



In your case, you have a class with no members, so in theory its size should be zero, however C ++ allocates one byte (due to the fact that objects must at least be addressed). So the result of the first distribution is 1 (if you fix your statements new/new[]

to return something, as long as you have UB). The second allocation returns 9 because of the way C ++ represents dynamic arrays, it puts some header somewhere (implementation is defined), so it recognizes that it is an array (so when called, the operator delete[]

latter behaves correctly) and maybe from - for filling.

+1


source







All Articles