Fun with C++ – Placement New

So, for some reason in the last few days I’ve been thinking about the old days of when I was a developer and really into C/C++. One of the things that I found interesting was placement new. In a nutshell it’s a way that you can instantiate a new object, but specify where in memory it will go. There are some interesting cases where it’s necessary such as cases where you might try to optimize by pre-allocating a bunch of memory and then re-using it. Kind of managing your own memory space. Anyway, this example shows how it’s done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "stdafx.h"
 
 
class Foo
{
public:
Foo() { strncpy(message, "Hello, World", 12);}
void * operator new (size_t, void * p) throw() { return p ; }
void operator delete (void *, void *) throw() { }
void printMessage() { printf("message is - %s\n", message); }
private:
char message[13];
};
 
int _tmain(int argc, _TCHAR* argv[])
{
char buf[sizeof(Foo)];
memset(buf, 0, sizeof(buf));
Foo *f = new((void *)buf) Foo();
printf("address of buf - %x\n", buf);
printf("address of f - %x\n", f);
printf("contents of buf - %s\n", buf);
f->printMessage();
buf[0] = 'h';
f->printMessage();
f->~Foo();
return 0;
}

Line 8 defines the constructor that placement new uses.
Line 9 defines the destructor.
Line 17 creates a buffer that is the size of a Foo object.
Line 19 instantiates a Foo object, but uses the buffer as the address of where the object will be instantiated.
Lines 20 and 21 print the addresses of the buffer and of f (the new object). They are the same.
Line 22 prints the contents of the buf, which is “Hello, World”. This is the value of the message variable in the object.
Line 23 prints the message.
Line 24 changes the first character in buf to be ‘h’. This should change it within f as well.
Line 25 shows that it changed.
Line 26 explicitly calls the destructor. That needs to be done when using placement new.

That’s about it! The example created a buffer, created an object in that buffer, changed the buffer, and showed that the object changed. Fun stuff!

Running it on my machine show-

address of buf - 31fbe0
address of f - 31fbe0
contents of buf - Hello, World
message is - Hello, World
message is - hello, World
This entry was posted in Code. Bookmark the permalink.