make_unique and perfect forwarding

后端 未结 6 1725
南方客
南方客 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 10:52

    Nice, but Stephan T. Lavavej (better known as STL) has a better solution for make_unique, which works correctly for the array version.

    #include 
    #include 
    #include 
    
    template 
    std::unique_ptr make_unique_helper(std::false_type, Args&&... args) {
      return std::unique_ptr(new T(std::forward(args)...));
    }
    
    template 
    std::unique_ptr make_unique_helper(std::true_type, Args&&... args) {
       static_assert(std::extent::value == 0,
           "make_unique() is forbidden, please use make_unique().");
    
       typedef typename std::remove_extent::type U;
       return std::unique_ptr(new U[sizeof...(Args)]{std::forward(args)...});
    }
    
    template 
    std::unique_ptr make_unique(Args&&... args) {
       return make_unique_helper(std::is_array(), std::forward(args)...);
    }
    

    This can be seen on his Core C++ 6 video.

    An updated version of STL's version of make_unique is now available as N3656. This version got adopted into draft C++14.

提交回复
热议问题