使独特和完美的转发为什么没有std::make_unique标准C+11库中的函数模板?我发现std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));有点冗长。下面这些不是更好吗?auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);这隐藏了new很好,只提到过一次类型。无论如何,下面是我试图实现的make_unique:template<typename T, typename... Args>std::unique_ptr<T> make_unique(Args&&... args){
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));}我花了好长时间才弄到std::forward需要编译的东西,但我不确定它是否正确。是吗?究竟是什么std::forward<Args>(args)...刻薄?编译器对此有何看法?
3 回答
![?](http://img1.sycdn.imooc.com/54586870000183e302200220-100-100.jpg)
慕妹3242003
TA贡献1824条经验 获得超6个赞
make_unique
#include <memory>#include <type_traits>#include <utility>template <typename T, typename... Args>std: :unique_ptr<T> make_unique_helper(std::false_type, Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...));}template <typename T, typename... Args>std: :unique_ptr<T> make_unique_helper(std::true_type, Args&&... args) { static_assert(std::extent<T>::value == 0, "make_unique<T[N]>() is forbidden, please use make_unique<T[]>()."); typedef typename std::remove_extent<T>::type U; return std::unique_ptr<T>(new U[sizeof...(Args)]{std::forward<Args>(args)...});}template <typename T, typename... Args>std::unique_ptr<T> make_unique(Args&&... args) { return make_unique_helper<T>(std::is_array<T>(), std::forward<Args>(args)...);}
![?](http://img1.sycdn.imooc.com/533e51f30001edf702000200-100-100.jpg)
aluckdog
TA贡献1847条经验 获得超7个赞
std::make_shared
std::shared_ptr<Type> ptr(new Type(...));
std::shared_ptr
std::make_shared
std::make_shared
std::shared_ptr<Type> ptr = new Type(...);
new
std::shared_ptr
std::make_shared<Type>(...)
std::shared_ptr
std::make_unique
- 3 回答
- 0 关注
- 372 浏览
添加回答
举报
0/150
提交
取消