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)
笔记:
所以make_unique(n)应该默认构造n T.
这些都不是无法回答的问题.但他们是尚未完全回答的问题.
| 归档时间: |
|
| 查看次数: |
8270 次 |
| 最近记录: |