Some people have advocated placement new.
That's dangerous, and the so far two usage examples have omitted crucial details like including the <new>
header, qualifying the call like ::new ...
, and how to clean up.
The safe solution is to define custom allocation and deallocation functions for your class, or for a class derived from your class. The example below shows the latter. Note that the virtual destructor is only there to support the class derivation; if you don't derive, you don't need it.
#include <stddef.h>
#include <iostream>
void* some_allocator_im_forced_to_use( size_t size )
{
std::cout << "Allocated " << size << " bytes." << std::endl;
return ::operator new( size );
}
void some_deallocator_im_forced_to_use( void* p, size_t size )
{
std::cout << "Deallocated " << size << " bytes." << std::endl;
::operator delete( p );
}
struct A
{
int x_;
A(): x_( 42 ) {}
virtual ~A() {}
};
struct CustomAllocedA
: A
{
void* operator new( size_t size )
{
return some_allocator_im_forced_to_use( size );
}
void operator delete( void* p, size_t size )
{
some_deallocator_im_forced_to_use( p, size );
}
};
int main()
{
A* const p = new CustomAllocedA;
std::cout << p->x_ << std::endl;
delete p;
}
Important: although this is "safe" in itself, and although this particular example is safe, the safety for your code ultimately rests on your custom allocator returning a pointer to properly aligned memory.
Cheers & hth.,