Re: new/delete for different POD types?
Alan McKenney posted:
Is static_cast<> legal here?
The following code is pefectly legal:
template<class T>
void DeletorVanilla( const void* const p )
{
delete static_cast<const T*>(p);
}
template<class T>
void DeletorArray( const void* const p )
{
delete [] static_cast<const T*>(p);
}
void PerformDeletion(const void* const p,
void (&Delete)(const void*)
)
{
Delete(p);
}
int main()
{
int * const p1 = new int;
int * const p2 = new int[5];
int (* const p3)[5] = new int [6][5];
int (* const p4)[5][7] = new int [6][5][7];
PerformDeletion( p1, DeletorVanilla<int> );
PerformDeletion( p2, DeletorArray<int> );
PerformDeletion( p3, DeletorArray<int[5]> );
PerformDeletion( p4, DeletorArray<int[5][7]> );
}
However, you can see how malloc and free are handier:
#include <cstdlib>
using std::malloc;
using std::free;
void PerformDeletion( void* const p )
{
free(p);
}
int main()
{
int * const p1 = static_cast<int*>(
malloc( sizeof(int) )
);
int * const p2 = static_cast<int*>(
malloc( sizeof(int[5]) )
);
int (* const p3)[5] = static_cast< int(*)[5] >(
malloc( sizeof(int[6][5]) )
);
int (* const p4)[5][7] = static_cast< int(*)[5][7] >(
malloc( sizeof(int[6][5][7]) )
);
PerformDeletion( p1 );
PerformDeletion( p2 );
PerformDeletion( p3 );
PerformDeletion( p4 );
}
-Tom?s
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]