gpt4 book ai didi

C++ 数组和 make_unique

转载 作者:IT老高 更新时间:2023-10-28 23:12:44 27 4
gpt4 key购买 nike

作为 this 的后续行动发布后我想知道它的 make_unique 实现如何与分配函数临时缓冲区数组一起使用,例如以下代码。

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

这可以替换为对 make_unique 的一些调用,然后会使用 []-version 的 delete 吗?

最佳答案

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

#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. new T[n] 应该只是默认构造 n 个 T。

所以 make_unique(n) 应该只是默认构造 n 个 T。

  1. 此类问题导致 make_unique 未在 C++11 中提出。另一个问题是:我们是否处理自定义删除器?

这些不是无法回答的问题。但它们是尚未完全回答的问题。

关于C++ 数组和 make_unique,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10149840/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com