Why is `make_unique` disallowed?

后端 未结 2 657
半阙折子戏
半阙折子戏 2020-12-05 13:35

Assume namespace std throughout.

The C++14 committee draft N3690 defines std::make_unique thus:

[n3

2条回答
  •  没有蜡笔的小新
    2020-12-05 14:10

    To me the third overload looks superfluous as does not change the fact that the other overloads won't match T[N] and it does not seem to help to generate better error messages. Consider the following implementation:

    template< typename T, typename... Args >
    typename enable_if< !is_array< T >::value, unique_ptr< T > >::type
    make_unique( Args&&... args )
    {
      return unique_ptr< T >( new T( forward< Args >( args )... ) );
    }
    
    template< typename T >
    typename enable_if< is_array< T >::value && extent< T >::value == 0, unique_ptr< T > >::type
    make_unique( const size_t n )
    {
      using U = typename remove_extent< T >::type;
      return unique_ptr< T >( new U[ n ]() );
    }
    

    When you try to call std::make_unique(1), the error message lists both candidates as disabled by enable_if. If you add the third, deleted overload, the error message lists three candidates instead. Also, since it is specified as =delete;, you can not provide a more meaningful error message in the third overload's body, e.g., static_assert(sizeof(T)==0,"array of known bound not allowed for std::make_shared");.

    Here's the live example in case you want to play with it.

    The fact that the third overload ended up in N3656 and N3797 is probably due to the history of how make_unique was developed over time, but I guess only STL can answer that :)

提交回复
热议问题