The syntax new (something) Type
is called placement
new. Like all new
, it calls an allocator function, then the
constructor of Type
. The allocator function has the signature:
void* operator new( size_t byteCount, something );
In other words, whatever you put in the parentheses is passed on as
additional arguments to the operator new
function.
In addition to the usual operator new
function, the standard defines
two other operator new
functions, which take additional arguments:
void* operator new( size_t byteCount, std::nothrow_t ) noexcept;
and
void* operator new( size_t byteCount, void* where ) noexcept;
Note that both are noexcept
. The first returns a null pointer if
allocation fails (rather than throwing bad_alloc
), and the second
simply returns where
. (The second is also known as placement new.
Which leads to no end of confusion: “placement new” can
refer to any extended new, or to jsut the one which takes a void*
.)
In your case, the second is the one being used, although I would
seriously question why: if the object type has a destructor, you will
have to do:
b->~MyClass();
free( b );
to delete it. (Placement new and explicit delete are usually used in
cases where you want to separate allocation from initialization. In an
implementation of std::vector
, for example, where the capacity can be
larger than the size.) About the only reason for it here that I can see
is that the object must be allocated in C++, but will be deleted in C
(and of course, it has a trivial destructor—otherwise, there's no
way C can correctly delete it).