Exception safety and make_unique

前端 未结 3 1365
盖世英雄少女心
盖世英雄少女心 2020-12-01 15:08

Just to clarify, using make_unique only adds exception safety when you have multiple allocations in an expression, not just one, correct? For example

         


        
3条回答
  •  粉色の甜心
    2020-12-01 15:23

    Not only when you have multiple allocations, but whenever you can throw at different places. Consider this:

    f(make_unique(), function_that_can_throw());
    

    Versus:

    f(unique_ptr(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(...)

    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).

提交回复
热议问题