Exception safety and make_unique

前端 未结 3 1358
盖世英雄少女心
盖世英雄少女心 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:30

    I'd think you'd be better off comparing things actually using std::unique_ptr:

    void f(std::unique_ptr);
    
    f(std::unique_ptr(new T));
    f(std::make_unique());
    

    Neither of these calls can leak if there is an exception being thrown. However

    void f(std::unique_ptr, std::unique_ptr);
    
    g(std::unique_ptr(new T), std::unique_ptr(new T));
    g(std::make_unique(), std::make_unique());
    

    In this case, the version using std::unique_ptr explicitly can leak if an exception is thrown (because the compiler might start evaluating the new-expressions before constructing either of the temporaries).

提交回复
热议问题