为什么C++ 11有`make_shared`而不是`make_unique`

Let*_*_Be 50 c++ c++11

可能重复:
make_unique和完美转发

为什么C++ 11有make_shared模板,但不是make_unique模板?

这使得代码非常不一致.

auto x = make_shared<string>("abc");
auto y = unique_ptr<string>(new string("abc"));
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 57

据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)

更新:原始更新已更新,重点已更改.

  • 在同一个`memory`标题中,`make_unique`也将在C++ 14中提供http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique (7认同)
  • @hyde谢谢.我更新了它,但新版本没有包含在此答案中的示例实现(可以在注释中找到). (2认同)