It has recently come to my attention that it is possible to use new and delete to allocate and release memory without calling constructors and destructors and to use new to call an object's constructor for already allocated memory. Can somebody point me to a semi official resource explaining how this is done? I am also interested in how this relates to overloading new.
To allocate memory without calling constructors, you call operator new directly (not through the new operator - don't confuse the two):
This is pretty much equivalent to calling malloc(), except of course that
void *mem = operator new(size);
1) new throws on allocation failure and
2) new can be overloaded.
Placement new is used to construct an object in pre-allocated memory:
For a semi-official resource, try Item 8 of Scott Meyers's More Effective C++.
Foo *pfoo = new (mem) Foo;
Are there some idioms or patterns there calling/overwriting operator new is useful?
The STL allocators basically do this, or a variant of it. Memory pools do it. Boost.Variant is built on placement new.
Overloading new is sometimes useful for special memory management strategies.
All in all, though, the cases where you need either feature are special, found on a case-by-case basis and do not come up in regular design patterns.
I'll see if I can get that book at my local library.
Originally Posted by CornedBee
What about deleting memory that has already been destroyed?
Use operator delete directly:
This thread wouldn't be complete without mentioning that there is no corresponding placement-delete.
To destruct an object without freeing its memory, use a direct destructor call: