make_unique and perfect forwarding

后端 未结 6 1861
南方客
南方客 2020-11-22 10:24

Why is there no std::make_unique function template in the standard C++11 library? I find

std::unique_ptr p(new SomeUs         


        
6条回答
  •  半阙折子戏
    2020-11-22 11:06

    std::make_shared isn't just shorthand for std::shared_ptr ptr(new Type(...));. It does something that you cannot do without it.

    In order to do its job, std::shared_ptr must allocate a tracking block in addition to holding the storage for the actual pointer. However, because std::make_shared allocates the actual object, it is possible that std::make_shared allocates both the object and the tracking block in the same block of memory.

    So while std::shared_ptr ptr = new Type(...); would be two memory allocations (one for the new, one in the std::shared_ptr tracking block), std::make_shared(...) would allocate one block of memory.

    That is important for many potential users of std::shared_ptr. The only thing a std::make_unique would do is be slightly more convenient. Nothing more than that.

提交回复
热议问题