Why use std::make_unique in C++17?

后端 未结 6 1934
旧巷少年郎
旧巷少年郎 2020-12-23 10:55

As far as I understand, C++14 introduced std::make_unique because, as a result of the parameter evaluation order not being specified, this was unsafe:



        
6条回答
  •  感动是毒
    2020-12-23 11:22

    Consider void function(std::unique_ptr(new A()), std::unique_ptr(new B())) { ... }

    Suppose that new A() succeeds, but new B() throws an exception: you catch it to resume the normal execution of your program. Unfortunately, the C++ standard does not require that object A gets destroyed and its memory deallocated: memory silently leaks and there's no way to clean it up. By wrapping A and B into std::make_uniques you are sure the leak will not occur:

    void function(std::make_unique(), std::make_unique()) { ... } The point here is that std::make_unique and std::make_unique are now temporary objects, and cleanup of temporary objects is correctly specified in the C++ standard: their destructors will be triggered and the memory freed. So if you can, always prefer to allocate objects using std::make_unique and std::make_shared.

提交回复
热议问题