unique_ptr没有使用默认删除器初始化 [英] unique_ptr is not getting init with default deleter
问题描述
当我使用 deleter
创建 unique_ptr
时,它会起作用:
When I create an unique_ptr
with deleter
, it works:
std::unique_ptr<Animal<Cat>, void(*)(Animal<Cat>*)> ptr(new Animal<Cat>, [](Animal<Cat> *ls) {
delete ls;
});
但是,此代码抛出错误:
But, this code is throwing error:
std::unique_ptr<Animal<Cat>, void(*)(Animal<Cat>*)> ptr;
ptr = std::unique_ptr<Animal<Cat>, void(*)(Animal<Cat>*)>(new Animal<Cat>, [](Animal<Cat> *ls) {
delete ls;
});
错误:
/usr/bin/../lib/c++/v1/memory:2561:13: error: static_assert failed "unique_ptr constructed with null function pointer deleter"
static_assert(!is_pointer<deleter_type>::value,
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: in instantiation of member function 'std::__1::unique_ptr<Animal<Cat>, void (*)(Animal<Cat> *)>::unique_ptr' requested here
std::unique_ptr<Animal<Cat>, void(*)(Animal<Cat>*)> ptr;
^
我的编译器版本:
Apple clang version 4.0 (tags/Apple/clang-421.0.60) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin12.4.0
Thread model: posix
Animal和Cat类很简单。这就是整个代码。
The Animal and Cat classes are trivial. This is the entire code.
推荐答案
显然不可能默认构造一个 unique_ptr
,带有删除器的指针类型。 unique_ptr
构造函数在§20.7.1.2.1[unique.ptr.single.ctor]中进行了详细说明,其中包括:
It as apparently not possible to default-construct a unique_ptr
with a pointer type for a deleter. The unique_ptr
constructors are detailed in §20.7.1.2.1 [unique.ptr.single.ctor] which says, among other things:
constexpr unique_ptr()noexcept;
4 备注:如果此构造函数使用模板
参数 D
[删除器类型]的指针类型或引用类型实例化,则程序为
4 Remarks: If this constructor is instantiated with a pointer type or reference type for the template
argument D
[the deleter type], the program is ill-formed.
类似于您想要的符合标准的东西
Something similar to what you want that is standard conforming:
unique_ptr<int, void(*)(int*)> ptr{nullptr,[](int*p){delete p;}};
// ...
ptr.reset(new int(42));
这篇关于unique_ptr没有使用默认删除器初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!