Matias Chara
Matias Chara

Reputation: 981

Two ways of using operator new() and operator delete()

what is the difference between this code:

void* raw_mem = operator new(sizeof(int)*4);
int *dynamicInt = static_cast<int*>(raw_mem);
dynamicInt[2] = 10;
operator delete(raw_mem);

and this code:

void* raw_mem = operator new[](sizeof(int)*4);//notice [] after new
int *dynamicInt = static_cast<int*>(raw_mem);
dynamicInt[2] = 10;
operator delete[](raw_mem);//notice [] after delete

are they strictly the same?

As per aschepler`s comment, my code is technically undefined behaviour. The working version of it is:

void* raw_mem = operator new(sizeof(int)*4);
int *dynamicInt = static_cast<int*>(raw_mem);
for(size_t i = 0;i<4;++i){
    new(&dynamicInt[i]) int(1);//initializes all elements to 1
}
//alternative version initializes only the first element:
//new(dynamicInt) int(10);
operator delete(raw_mem);

Upvotes: 0

Views: 85

Answers (1)

Mestkon
Mestkon

Reputation: 4046

There is no difference according to cppreference. The standard library just forwards operator new[] and operator delete[] to operator new and operator delete.

Upvotes: 1

Related Questions