The new operator in C++ |
Written by Eli Bendersky | ||||
Tuesday, 29 March 2011 | ||||
Page 2 of 3
Allocation - an exampleIt’s educational to look at the way the new operator works in C++. Allocation is a two step process:
The C++ FAQ presents a really nice code sample I’d like to reproduce here: When you write this code: Foo* p = new Foo(); what the compiler generates is functionally similar to: Foo* p; // don't catch exceptions thrown by the The funny syntax inside the try statement is called "placement new", and we’ll discuss it shortly. For completeness’ sake, let’s see a similar breakdown for freeing an object with delete, which is also a two-step process:
So: delete p; Is equivalent to: if (p != NULL) { p->~Foo(); operator delete(p); } Note the check for NULL. It's the reason for delete p being safe even when p is NULL – another C++ FAQ. This is also a good place to repeat something I’ve mentioned in the first section of this article – if a class has its own operator new or operator delete, these get invoked instead of the global functions when an object is allocated or deallocated. Placement newNow, back to that "placement new" we saw in the code sample above. It happens to be a real syntax we can use in our C++ code. First, I want to briefly explain how it works. Then, we’ll see when it can be useful. Calling placement new directly skips the first step of object allocation. We don’t ask for memory from the OS. Rather, we tell it where there’s memory to construct the object in. Remember, to ensure that the location that pointer goes to has enough memory for the object, and that the pointer is also correctly aligned. The following code sample should clarify this: int main(int argc, const char* argv[]) { // A "normal" allocation. Asks the OS For a particular run on my machine it prints: Addr of iptr = 0x8679008 Addr of mem = 0xbfdd73d8 Addr of iptr2 = 0xbfdd73d8 As you can see, the mechanics of placement new are quite simple. What’s more interesting is the question – why would we need something like this? It turns out placement new is quite useful in a few scenarios:
|
||||
Last Updated ( Tuesday, 29 March 2011 ) |