Re: c++ delete operator parameters
Michael Crawley wrote:
If I can allocate memory on a custom memory pool like using 'new(heap)
TypeConstructor(),' why is it not allowed to deallocate by invoking
'delete(heap) valueReference' or 'delete[](valueReference, heap)?' I have to
invoke the destructor explicitly and invoke the static delete operator
explicitly for the type like 'var->~VarType(); VarType::operator delete(var,
heap).'
Unfortunately, I don't think the C++ memory allocation overriding system
is well designed. Really, you have to fall back to your own design if
you have advanced needs.
However, after a quick Google, I have found others to suggest I am
mistaken, but I cannot get it to compile without some error.
They are mistaken, not you.
I know to have
overloaded 'delete' operators in order to properly cleanup memory if an
exception is thrown within a constructor after invoking a 'new' operator with
the same parameter list, but why can I not get to use them regularly?
They aren't designed to be used that way. Unlike operator new, it is
easy to write a deleting template function (e.g.
template <class T>
void destroy(Heap& h, T* t) //add more args if desired
{
if (t)
{
t->~T();
h.free(t);
}
}
or similar). That can't be done for new, since you would need perfect
argument passing to get the constructor parameters in, and C++ doesn't
yet have perfect parameter passing.
Code to destroy objects should generally be restricted to a very small
number of classes in any case (e.g. containers, smart pointers, etc.).
I have
also notice that you can code a completely bogus invocation to delete like
'delete(false, false, false, false, var),' but as long as the last argument
is a pointer, VS2003 will take and resolve it into assembly as an explicit
call to the destructor without calling any 'delete' operator.
The ordinary (global or class) operator delete function should have been
called.
Tom