开发者

Using allocators

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;
    all开发者_StackOverflow中文版oc.destroy(ptr);
    alloc.deallocate(ptr, 1);
};


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜