Reputation: 42379
The following code is excerpted from the latest libc++
header <functional>
of clang 3.4:
At line 1636:
typedef __allocator_destructor<_Ap> _Dp;
unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1));
::new (__hold.get()) _FF(_VSTD::move(__f), _Alloc(__a));
__f_ = __hold.release();
Why use unique_ptr
to manage dynamically allocated storage here? Please note __hold
will never call its deleter
because it finally releases the control of its internal storage!
Why not just write as follows:
__f_ = __a.allocate(1);
::new (__f_) _FF(_VSTD::move(__f), _Alloc(__a));
Upvotes: 1
Views: 198
Reputation: 66961
__f_ = __a.allocate(1);
Alright, you've allocated memory and stored the pointer.
::new (__f_) _FF(_VSTD::move(__f), _Alloc(__a));
This throws an exception, and the stack unwinds. Oops, you just leaked your dynamic memory! The obvious way to prevent memory leaks is.... std::unique_ptr
.
Upvotes: 2