为什么 C++11 有 `make_shared` 而没有 `make_unique`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12580432/
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
Why does C++11 have `make_shared` but not `make_unique`
提问by ?imon Tóth
Possible Duplicate:
make_unique and perfect forwarding
可能的重复:
make_unique 和完美转发
Why does C++11 have a make_shared
template, but not a make_unique
template?
为什么C++11有make_shared
模板,而没有make_unique
模板?
This makes code very inconsistent.
这使得代码非常不一致。
auto x = make_shared<string>("abc");
auto y = unique_ptr<string>(new string("abc"));
回答by juanchopanza
According to Herb Sutter in this articleit was "partly an oversight". The article contains a nice implementation, and makes a strong case for using it:
根据 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)... ) );
}
Update: The original update has been updatedand the emphasis has changed.
更新:原更新已更新,重点已更改。