C++ C++;数组并使_唯一
作为帖子的后续内容,我想知道它的C++ C++;数组并使_唯一,c++,arrays,c++11,unique-ptr,raii,C++,Arrays,C++11,Unique Ptr,Raii,作为帖子的后续内容,我想知道它的make_unique实现如何分配函数临时缓冲区数组,如下面的代码 f() { auto buf = new int[n]; // temporary buffer // use buf ... delete [] buf; } 可以用调用make_unique来替换它吗?然后会使用[]-版本的delete吗?我用这个代码得到了它: #include <memory> #include <utility> namespace
make_unique
实现如何分配函数临时缓冲区数组,如下面的代码
f()
{
auto buf = new int[n]; // temporary buffer
// use buf ...
delete [] buf;
}
可以用调用
make_unique
来替换它吗?然后会使用[]
-版本的delete吗?我用这个代码得到了它:
#include <memory>
#include <utility>
namespace Aux {
template<typename Ty>
struct MakeUnique {
template<typename ...Args>
static std::unique_ptr<Ty> make(Args &&...args) {
return std::unique_ptr<Ty>(new Ty(std::forward<Args>(args)...));
}
};
template<typename Ty>
struct MakeUnique<Ty []> {
template<typename ...Args>
static std::unique_ptr<Ty []> make(Args &&...args) {
return std::unique_ptr<Ty []>(new Ty[sizeof...(args)]{std::forward<Args>(args)...});
}
};
}
template<typename Ty, typename ...Args>
std::unique_ptr<Ty> makeUnique(Args &&...args) {
return Aux::MakeUnique<Ty>::make(std::forward<Args>(args)...);
}
#包括
#包括
名称空间辅助{
模板
结构MakeUnique{
模板
静态标准::唯一的ptr生成(参数&&…参数){
返回std::unique_ptr(新的Ty(std::forward(args)…);
}
};
模板
结构MakeUnique{
模板
静态标准::唯一的ptr生成(参数&&…参数){
返回std::unique_ptr(新的Ty[sizeof…(args)]{std::forward(args)…});
}
};
}
模板
std::unique_ptr makeUnique(Args&&…Args){
返回Aux::MakeUnique::make(标准::转发(参数)…);
}
这里是另一个解决方案(除了Mike的):
#包括
#包括
#包括
模板
typename std::启用\u如果
<
!std::is_array::value,
std::unique\u ptr
>::类型
使_唯一(Args&&…Args)
{
返回std::unique_ptr(新的T(std::forward(args)…);
}
模板
typename std::启用\u如果
<
std::is_array::value,
std::unique\u ptr
>::类型
使_唯一(标准::大小\u t n)
{
typedef typename std::remove_extent::type RT;
返回std::unique_ptr(新RT[n]);
}
int main()
{
自动p1=使_唯一(3);
自动p2=使_唯一(3);
}
注:
这些都不是无法回答的问题。但这些问题还没有完全得到回答。。。。但是这些问题在C++14中已经(部分)得到了回答,现在使_唯一了。@einpoklum:正确。注意问答上的日期。阅读答案:不,没有简单的答案:(
#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);
}