class X
{
public:
X (int);
// ...
};
We can place objects anywhere by providing an allocator function with extra arguments and then supplying such extra arguments when using new:
void* operator new(size_t, void *p)
{
return p;
} // explicit placement operator
void* buf = reinterpret_cast<void*>(0xF00F); // significant address
X*p2 = new(buf)X; //construct an X at ‘buf;’ invokes: operator new(sizeof(X),buf)
What does it means? What is reinterpret_cast and what it is doing here?
explain broadly…..
There are two ways you can call
operator new. The first way I’m assuming you’re familiar with:With this usage you’re telling the compiler to do two things:
operator newto do something different.Now the second form of
operator newpresented in your code:With this usage you’re basically telling the compiler do not allocate space for X. Instead use the space provided by buf to construct this instance of X. Step 2 is still performed but step 1 is skipped.
The
reinterpret_cast<void *>here is essentially telling the compiler whatever is at address 0xF00F, treat it as some generic data — no type or size is associated with this data. This is equivalent to doing a raw C-style cast:This is done to satisfy operator new’s function signature:
Note the generic pointer
void *p— that will take on buf’s value passed in earlier. The cast is there to make their ‘types’ match. Also note that 0xF00F technically isn’t a valid address but we’ll pretend it is for this example.And that is what the code above is doing, explained broadly.