如何在C++ 11中实现make_unique函数?

use*_*020 27 c++ unique-ptr c++11 c++14

我的编译器不支持make_unique.怎么写一个?

template< class T, class... Args > unique_ptr<T> make_unique( Args&&... args );
Run Code Online (Sandbox Code Playgroud)

sas*_*hka 45

Stephan T. Lavavej(也称为STL)的版本最初建议将此函数添加到C++ 14中

#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>

namespace std {
    template<class T> struct _Unique_if {
        typedef unique_ptr<T> _Single_object;
    };

    template<class T> struct _Unique_if<T[]> {
        typedef unique_ptr<T[]> _Unknown_bound;
    };

    template<class T, size_t N> struct _Unique_if<T[N]> {
        typedef void _Known_bound;
    };

    template<class T, class... Args>
        typename _Unique_if<T>::_Single_object
        make_unique(Args&&... args) {
            return unique_ptr<T>(new T(std::forward<Args>(args)...));
        }

    template<class T>
        typename _Unique_if<T>::_Unknown_bound
        make_unique(size_t n) {
            typedef typename remove_extent<T>::type U;
            return unique_ptr<T>(new U[n]());
        }

    template<class T, class... Args>
        typename _Unique_if<T>::_Known_bound
        make_unique(Args&&...) = delete;
}
Run Code Online (Sandbox Code Playgroud)

编辑:更新代码到N3656标准修订版

  • 请注意,我们不允许将内容放入std :: like.如果我不得不添加`make_unique`,我宁愿使用自己的实用程序命名空间. (4认同)
  • @BenJackson当正确使用`make_unique`时,目的是永远不会匹配`_Known_bound`版本.如果有人试图将它用作`make_unique <T [N]>()`它将匹配`_Known_bound`版本并导致错误. (2认同)
  • 将此定义包含在C++代码中的最佳方法是什么,最终可以在stdc ++中提供make_unique的环境中编译? (2认同)
  • @AndreasYankopolus我建议#if __cplusplus == 201103L ... #endif(请参阅https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html末尾附近的__cplusplus条目) (2认同)

Ali*_*Ali 31

复制自make_unique和完美转发(Herb Sutter的博客中给出了相同的内容)

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
Run Code Online (Sandbox Code Playgroud)

如果你在VC2012中需要它,请参阅在VS2012中有没有办法写make_unique()?


然而,如果sasha.sochka的答案中的解决方案与编译器一起编译,我会选择那个.这更精细,也适用于数组.