Skip to main content

What is placement new?

It's a way to pass parameters to the allocator rather than just to the constructor.
Allocating an object from the heap, such as new Fred(5,7), is a two-step process: first an appropriately sized and aligned block of uninitialized memory is allocated from the heap, then the constructor is called with the this pointer pointing to that block of memory. Parameters are often passed to the constructor (for example, the above example passes (5,7)), but occasionally parameters also must be passed to the allocation step. For example, if there was a special allocator that used a particular pool of memory, it might be necessary to pass a reference to that pool of memory to the allocation step, that is, to new itself: new(myPool) Fred(5,7).
Another common reason to pass a parameter for the allocation step is to pass a pointer to a particular preallocated region of memory. For example, if pointer p is a void* that points to a pile of memory that is at least sizeof(Fred) bytes long and is appropriately aligned, one could say new(p) Fred(5,7). This would construct a Fred object at the location pointed to by p (that is, it would pass p as the this pointer to Fred's constructor) and would ultimately return a Fred* that would point to the same location that void* p points to. For example,
#include // Must #include this to use placement new
using namespace std;
#include "Fred.hpp" // Declaration of class Fred

void sample() throw()
{
char memory[sizeof(Fred)]; // Line 1
void* p = memory; // Line 2
Fred* f = new(p) Fred(); // Line 3 (be careful here!)
// The pointers f and p will be equal
// ...
}
Line 1 creates an array of sizeof(Fred) bytes of memory, which is big enough to hold a Fred object. Line 2 creates a pointer p that points to the first byte of this memory (experienced C programmers will note that this step is unnecessary; it's there only to make the code more obvious). Line 3 essentially calls the constructor Fred::Fred(). The this pointer in the Fred constructor is equal to p. The returned pointer f is equal to p.
Passing a void* pointer with the placement new syntax should be used only when it is essential to place an object at a particular location. For example, when writing an operating system, the placement new syntax could be used to place a Clock object at a particular memory-mapped I/O timer device. Neither the compiler nor the runtime system make any attempt to check whether the passed pointer points to a region of memory that is big enough and is properly aligned for the object being created. For example, if Fred objects need to be aligned on a 4-byte boundary but the supplied pointer p isn't properly aligned, it could be a serious (and subtle) disaster. You have been warned.
Also, the programmer takes sole responsibility to deallocate the object when the placement new syntax is used. This is done by explicitly calling the destructor, which is one of the few times a destructor should be called explicitly:
void sample2() throw()
{
char memory[sizeof(Fred)];
void* p = memory;
Fred* f = new(p) Fred();
// ...
f->~Fred();
}
(1) Explicitly call the destructor for the placed object

Comments

Popular posts from this blog

MFC - Microsoft Foundation Classes Design Patterns

1 Introduction This paper describes the use of object-oriented software design patterns, as presented in Design Patterns: Elements of Reusable Object-Oriented Software by Gamma et al., within the Microsoft Foundation Class Library (MFC). MFC is used for implementing applications for Microsoft Windows operating systems. Because of the size of the MFC library, a complete analysis would have been beyond the scope of this assignment. Instead, we identified various possible locations for design patterns, using the class hierachy diagram of MFC, and studied the source carefully at these locations. When we did not find a pattern where we expected one, we have documented it anyway, with examples of how the particular problem could have been solved differently, perhaps more elegantly, using design patterns. We have included a brief introduction to MFC in Section 2 , as background information. The analysis has been split into three parts, with one section for each major design pattern ca...

Explain Polymorphism and Flavors of Polymorphism...

Polymorphism is the ability of different objects to react in an individual manner to the same message. This notion was imported from natural languages. For example, the verb "to close" means different things when applied to different objects. Closing a door, closing a bank account, or closing a program's window are all different actions; their exact meaning is determined by the object on which the action is performed. Most object-oriented languages implement polymorphism only in the form of virtual functions. But C++ has two more mechanisms of static (meaning: compile-time) polymorphism: Operator overloading. Applying the += operator to integers or string objects, for example, is interpreted by each of these objects in an individual manner. Obviously, the underlying implementation of += differs in every type. Yet, intuitively, we can predict what results are. Templates. A vector of integers, for example, reacts differently from a vector of string objects when it receives ...

• Why might you need exception handling be used in the constructor when memory allocation is involved?

Your first reaction should be: "Never use memory allocation in the constructor." Create a separate initialization function to do the job. You cannot return from the constructor and this is the reason you may have to use exception handling mechanism to process the memory allocation errors. You should clean up whatever objects and memory allocations you have made prior to throwing the exception, but throwing an exception from constructor may be tricky, because memory has already been allocated and there is no simple way to clean up the memory within the constructor.