Tech Journal Back to Tech Journal

How can I call new in C++ and force it to init a given memory location? Alternatively, how can I tell it not to allocate any memory dynamically?

There's a header in the standard C++ named <new>. Once you include it, you can call upon the "placement new" using a syntax like

new (pointer_to_preallocated_memory) ClassName();

And now pointer_to_preallocated_memory will contain an initialized instance of ClassName. This is great for using C++ patterns with stack memory, pre-allocated memory such as shared memory between processes.

No memory has been allocated, and therefore you must be careful not to call delete on that memory, but rather to call the destructor directly, using syntax like:

((ClassName*)pointer_to_preallocated_memory)->~ClassName();

 Example:

#include <stdio.h>
#include <new>

class MyClass {
public:
MyClass() {
printf("constructed 0x%08x\n", (unsigned)this);
}

~MyClass() {
printf("destructed 0x%08x\n", (unsigned)this);
}
};


int main(int argc, char *argv[])
{
char buf[sizeof(MyClass)];

// Call the constructor on a specific blob of memory
::new(buf) MyClass();

// Call the destructor on that memory
((MyClass *)buf)->~MyClass();
return 0;
}

Thanks to http://www.omnigroup.com/mailman/archive/macosx-dev/2003-September/048403.html

Last updated on 2008-05-14 00:27:39 -0700, by Shalom Craimer

Back to Tech Journal