make_unique和完美转发 [英] make_unique and perfect forwarding

查看:227
本文介绍了make_unique和完美转发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在标准C ++ 11库中没有 std :: make_unique 函数模板?我找到

  std :: unique_ptr< SomeUserDefinedType> p(new SomeUserDefinedType(1,2,3)); 

有点冗长。下面是不是更好?

  auto p = std :: make_unique< SomeUserDefinedType>(1,2,3) ; 

这隐藏了 new 类型一次。



无论如何,这里是我尝试执行 make_unique

 模板< 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)... 是什么意思? C ++标准化委员会主席Herb Sutter在他的 http://herbsutter.com/gotw/_102/\">博客


那C ++ 11不' t包括 make_unique 部分是疏忽,并且几乎肯定会在将来添加。


他还给出了一个与OP给出的实现相同的实现。



Edit: std :: make_unique 现在是 C ++ 14 的一部分。


Why is there no std::make_unique function template in the standard C++11 library? I find

std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));

a bit verbose. Wouldn't the following be much nicer?

auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);

This hides the new nicely and only mentions the type once.

Anyway, here is my attempt at an implementation of 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)...));
}

It took me quite a while to get the std::forward stuff to compile, but I'm not sure if it's correct. Is it? What exactly does std::forward<Args>(args)... mean? What does the compiler make of that?

解决方案

Herb Sutter, chair of the C++ standardization committee, writes on his blog:

That C++11 doesn’t include make_unique is partly an oversight, and it will almost certainly be added in the future.

He also gives an implementation that is identical with the one given by the OP.

Edit: std::make_unique now is part of C++14.

这篇关于make_unique和完美转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆