Other ways os using new/delete operators

This post consistis of notes I took while reading this nice article: http://eli.thegreenplace.net/2011/02/17/the-many-faces-of-operator-new-in-c/

You can alloc more memory than necessary using the raw operator new. For example:

char *mem = (char*) ::operator new(10);

It’s the same as

char *mem = (char*) malloc(10);

With the difference that operator new is overloadable.

When you use the regular new operator for a class, it also call the constructor, so the two lines of code below are not the same:

Foo *foo = new Foo();
Foo *foo2 = (Foo*) operator new(sizeof(Foo));

To simulate the same behaviour, we have to use another form of calling the new operator that is called “placement new”. In this operator, you pass as argument the address of memory where the object will be placed so you can allocate it a priori:

Foo *p;
void *buf = operator new(sizeof(Foo));
p = new(buf) Foo();
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s