【问题标题】:Why does C++11 have `make_shared` but not `make_unique` [duplicate]为什么C ++ 11有`make_shared`但没有`make_unique` [重复]
【发布时间】:2012-09-25 09:50:11
【问题描述】:

可能重复:
make_unique and perfect forwarding

为什么C++11有make_shared模板,却没有make_unique模板?

这使得代码非常不一致。

auto x = make_shared<string>("abc");
auto y = unique_ptr<string>(new string("abc"));

【问题讨论】:

  • 可能是因为unique 需要构造一个对象,他们认为最好显式完成
  • 不一致的不是代码,而是库。
  • unique_ptr 的复制构造函数是私有的。所以 make_unique 没有“返回值优化”是行不通的。我的猜测是根据语言规范,这种优化不是强制性的。

标签: c++ c++11


【解决方案1】:

根据this article 中的 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)... ) );
}

更新:原更新has been updated,重点有所改变。

【讨论】:

猜你喜欢
  • 2019-10-09
  • 2017-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-07
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多