Josuttis氏は、可能なアロケータ使用(15章)についての例を示します。このコードにはメモリリークの可能性はありますか?
void vector<T,Allocator>::reserve(size_type size)
{
//allocate new memory for size elements
T* newmem = alloc.allocate (size);
//copy old elements into new memory
uninitialized_copy(elems,elems+numElems,newmem);
uninitialized_copyが失敗した場合はどうなりますか?/
template <class InputIter, class ForwIter>
ForwIter uninitialized_copy(lnputIter beg, InputIter end, ForwIter dest)
{
typedef typename iterator_traits<ForwIter>::value_type VT;
ForwIter save(dest);
try {
for (; beg!=end; ++beg,++dest) {
new (static_cast<void*>(&*dest))VT(*beg);
}
return dest;
}
catch (...) {
for (; save!=dest; ++save) {
save->~VT();
}
throw; // will ::operator delete() be called to free the previously allocated memory?
}
}
C++ 11では、 'try/catch'ではなく' unique_ptr'を使うと思いますが、それは私だけです。 – ildjarn
@ildjarn:* what *への一意のポインタ?ここでは、連続した 'T'オブジェクトのシーケンスを設定しています。 'unique_ptr'おそらく? –
'unique_ptr'にカスタムディテッターがあります。 RAIIは 'try/catch'よりも賢明ではありませんか? –
ildjarn