C ++数组和make_unique [英] C++ Arrays and make_unique

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

问题描述

作为这篇文章的后续文章,我想知道它如何实现可以分配功能临时缓冲区数组,例如下面的代码.

As a follow up to this post I wonder how its implementation of make_unique plays with allocating function-temporary buffer arrays such as in the following code.

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

可以将其替换为对make_unique的调用,然后将使用[]版本的delete吗?

Can this be replaced with some call to make_unique and will the []-version of delete be used then?

推荐答案

这是另一种解决方案(除了Mike的解决方案):

Here is another solution (in addition to Mike's):

#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);
}

注意:

  1. 新T [n]应该只是默认构造n个T.

因此make_unique(n)应该只默认构造n个T.

So make_unique(n) should just default construct n T's.

  1. 像这样的问题导致make_unique不在C ++ 11中提出.另一个问题是:我们可以处理自定义删除器吗?

这些不是无法回答的问题.但是,这些问题尚未得到完全解答.

These are not unanswerable questions. But they are questions that haven't yet been fully answered.

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

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