Question

Are these versions of new and delete are exception safe? Any possible pitfalls?

Assume that customized_allocator_type is STL compatible. Also assume that the allocator's constructor doesn't have any side effect and all instances are equivalent.

Thanks in advance for your input!

template <typename T>
inline T * customized_new(const T& t)
{
    customized_allocator_type<T> alloc;
    T * ptr = alloc.allocate(1);

    if (ptr==0)
        throw std::bad_alloc();

    try {
        alloc.construct(ptr, t);
    } catch (...) {
        alloc.deallocate(ptr, 1);
        throw;
    }

    return ptr;
}


template <typename T>
inline void customized_delete(T * ptr)
{
    if (ptr==0)
        return;

    customized_allocator_type<T> alloc;
    alloc.destroy(ptr);
    alloc.deallocate(ptr, 1);
};
Was it helpful?

Solution

This is (at best) redundant:

if (ptr==0)
    throw std::bad_alloc();

If customized_allocator_type is meeting the standard library allocator requirements then it must raise an exception if storage could not be obtained. Returning null from allocate would not be correct.

OTHER TIPS

If the behavior of customized_allocator_type's construct() function is known that it doesn't deallocate the memory on exception, then your solution is good.

Note: there is a typo in customized_delete() check for null pointer - it should be:

if (ptr == 0)
  return;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top