C++数组和make_unique

Nor*_*löw 12 c++ arrays raii unique-ptr c++11

作为这篇文章的后续内容,我想知道如何make_unique通过分配函数临时缓冲区数组来实现它的播放,如下面的代码所示.

f()
{
  auto buf = new int[n]; // temporary buffer
  // use buf ...
  delete [] buf;
}
Run Code Online (Sandbox Code Playgroud)

可这与一些调用所替换,以make_unique与将[]的删除-version被继续使用?

How*_*ant 18

这是另一个解决方案(除了迈克):

#include <type_traits>
#include <utility>
#include <memory>

template <class T, class ...Args>
typename std::enable_if
<
    !std::is_array<T>::value,
    std::unique_ptr<T>
>::type
make_unique(Args&& ...args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

template <class T>
typename std::enable_if
<
    std::is_array<T>::value,
    std::unique_ptr<T>
>::type
make_unique(std::size_t n)
{
    typedef typename std::remove_extent<T>::type RT;
    return std::unique_ptr<T>(new RT[n]);
}

int main()
{
    auto p1 = make_unique<int>(3);
    auto p2 = make_unique<int[]>(3);
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. 新T [n]应该默认构造n T'.

所以make_unique(n)应该默认构造n T.

  1. 像这样的问题导致make_unique没有在C++ 11中提出.另一个问题是:我们是否处理自定义删除工具?

这些都不是无法回答的问题.但他们是尚未完全回答的问题.