unique_ptr 中原始指针的默认删除器
Default deleter for raw pointer in unique_ptr
使用 std::unique_ptr
依赖默认删除器是否安全?
我想这样使用它:
uint8_t* binaryData = new uint8_t[binaryDataSize];
std::unique_ptr<uint8_t> binPtr(binaryData);
因此 std::unique_ptr
中的默认删除器如下所示:
template<typename _Up>
typename enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type
operator()(_Up* __ptr) const
{
static_assert(sizeof(_Tp)>0,
"can't delete pointer to incomplete type");
delete [] __ptr;
}
从我的角度来看,使用 new[]
分配的原始指针是安全的,而使用 std::malloc
分配的原始指针不安全。
我错过了什么吗?有更好的解决方案吗?
So the default deleter in std::unique_ptr
looks like this:
这是数组的默认删除器。您只会在使用 std::unique_ptr<T[]>
时点击删除器,而不会在使用 std::unique_ptr<T>
.
时点击删除器
From my point of view it's safe to use for raw pointers allocated by new[]
只要你用std::unique_ptr<T[]>
,就可以。您应该使用 std::make_unique
来避免这些问题。
raw pointers allocated by std::malloc
std::unique_ptr
不支持用 malloc
分配的指针。无论如何,您不应该在 C++ 中使用 malloc
。
应该是std::unique_ptr<uint8_t[]>
,否则默认删除器不是那个,而是调用plain delete
的那个,不匹配会触发UB。
如果分配给 std::malloc
,则根本无法使用默认删除器,您需要提供自己的调用 std::free
.
的删除器
使用 std::unique_ptr
依赖默认删除器是否安全?
我想这样使用它:
uint8_t* binaryData = new uint8_t[binaryDataSize];
std::unique_ptr<uint8_t> binPtr(binaryData);
因此 std::unique_ptr
中的默认删除器如下所示:
template<typename _Up>
typename enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type
operator()(_Up* __ptr) const
{
static_assert(sizeof(_Tp)>0,
"can't delete pointer to incomplete type");
delete [] __ptr;
}
从我的角度来看,使用 new[]
分配的原始指针是安全的,而使用 std::malloc
分配的原始指针不安全。
我错过了什么吗?有更好的解决方案吗?
So the default deleter in
std::unique_ptr
looks like this:
这是数组的默认删除器。您只会在使用 std::unique_ptr<T[]>
时点击删除器,而不会在使用 std::unique_ptr<T>
.
From my point of view it's safe to use for raw pointers allocated by
new[]
只要你用std::unique_ptr<T[]>
,就可以。您应该使用 std::make_unique
来避免这些问题。
raw pointers allocated by
std::malloc
std::unique_ptr
不支持用 malloc
分配的指针。无论如何,您不应该在 C++ 中使用 malloc
。
应该是std::unique_ptr<uint8_t[]>
,否则默认删除器不是那个,而是调用plain delete
的那个,不匹配会触发UB。
如果分配给 std::malloc
,则根本无法使用默认删除器,您需要提供自己的调用 std::free
.