Not only when you have multiple allocations, but whenever you can throw at different places. Consider this:
f(make_unique<T>(), function_that_can_throw());
Versus:
f(unique_ptr<T>(new T), function_that_can_throw());
In the second case, the compiler is allowed to call (in order):
new T
function_that_can_throw()
unique_ptr<T>(...)
Obviously if function_that_can_throw
actually throws then you leak. make_unique
prevents this case.
And of course, a second allocation (as in your question) is just a special case of function_that_can_throw()
.
As a general rule of thumb, just use make_unique
so that your code is consistent. It is always correct (read: exception-safe) when you need a unique_ptr
, and it doesn't have any impact on performance, so there is no reason not to use it (while actually not using it introduces a lot of gotchas).
make_unique
orunique_ptr
in your examples because?multiple allocations in an expression
but each of those allocations vianew T
is a separate expression, so you have the opposite: one allocation per each of multiple expressions. That the function call is itself an expression containing the other 2 doesn't change that. But aside from the wording, you were on the right track. By my reading, the rule, as formulated by Sutter, is to perform each allocation within its own statement or sequence them by returning from a separate function call, thereby avoiding weird ordering & leaks: gotw.ca/gotw/056.htm (oldie-but-goodie)