Re: deletion of mem alloated using placement new
On 31 Ago, 11:48, Gianni Mariani <gi3nos...@mariani.ws> wrote:
Anonymous wrote:
I am writing memory allocation class policies for a template class.
I have defined one allocated like this:
template <class T>
struct myMallocAllocator
{
static T* Allocate()
{
void * ptr = calloc(1, sizeof(T));
if (ptr)
return new(ptr) T ;
else
return 0 ;
The C++ thing is to throw std::bad_alloc and not return 0.
}
static void DeAllocate(T *ptr)
{
if(ptr);
ptr->~T() ;
if (ptr) {
ptr->~T();
free( static_cast<void*>(ptr) );
}
}
};
Am i deallocating correctly?
whats with the destructor calling? when you delete a pointer the
destructor is automatically called.
also is perfect valid to delete a NULL pointer, so no need to check if
it exists.
also why use malloc/calloc and free? why not new/delete? i cant see a
valid reason in this example to not use the standard c++ allocate/
deallocate operators.
so simple, no need to complicate it:
template <class T>
class Allocator
{
public:
static T* Allocate()
{
return new T;
}
static void Deallocate( T* t )
{
delete t;
}
};
class Test
{
public:
Test()
{
std::cout << "Test::Test()" << std::endl;
}
~Test()
{
std::cout << "Test::~Test()" << std::endl;
}
};
int main( int argc, char** argv )
{
Test *t = Allocator<Test>::Allocate();
Allocator<Test>::Deallocate( t );
return 0;
}