使用分配器
这些版本的new和delete是否异常安全?有什么可能的陷阱吗?
假设 customized_allocator_type 与 STL 兼容。还假设分配器的构造函数没有任何副作用,并且所有实例都是等效的。
预先感谢您的意见!
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);
};
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);
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这(充其量)是多余的:
如果
customized_allocator_type
满足标准库分配器要求,那么如果无法获取存储,它必须引发异常。从allocate
返回 null 是不正确的。This is (at best) redundant:
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 fromallocate
would not be correct.如果customized_allocator_type的construct()函数的行为已知它不会在异常时释放内存,那么你的解决方案是好的。
注意:customized_delete() 检查空指针时存在拼写错误 - 应该是:
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: