如何在 C++11 中实现 make_unique 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17902405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement make_unique function in C++11?
提问by user1899020
My compiler doesn't support make_unique. How to write one?
我的编译器不支持 make_unique。一个怎么写?
template< class T, class... Args > unique_ptr<T> make_unique( Args&&... args );
回答by sasha.sochka
Version by Stephan T. Lavavej (also known by STL) who originally proposed adding this function to C++14
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;
}
EDIT: updated code to the N3656standard revision
编辑:将代码更新为N3656标准修订版
回答by Ali
Copied from make_unique and perfect forwarding(the same is given in Herb Sutter's blog)
复制自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)...));
}
If you need it in VC2012, see Is there a way to write make_unique() in VS2012?
如果您在 VC2012 中需要它,请参阅有没有办法在 VS2012 中编写 make_unique()?
Nevertheless, if the solution in sasha.sochka's answercompiles with your compiler, I would go with that one. That is more elaborate and works with arrays as well.
尽管如此,如果sasha.sochka 的答案中的解决方案与您的编译器一起编译,我会选择那个。这更复杂,也适用于数组。