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.

#include "stdafx.h"

class Foo
  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); }
  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);
  buf[0] = 'h';
  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