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

后端 未结 6 1907
旧巷少年郎
旧巷少年郎 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:33

    Every use of new has to be extra carefully audited for lifetime correctness; does it get deleted? Only once?

    Every use of make_unique doesn't for those extra characteristics; so long as the owning object has "correct" lifetime, it recursively makes the unique pointer have "correct".

    Now, it is true that unique_ptr(new Foo()) is identical in all ways1 to make_unique(); it just requires a simpler "grep your source code for all uses of new to audit them".


    1 actually a lie in the general case. Perfect forwarding isn't perfect, {}, default init, arrays are all exceptions.

提交回复
热议问题