Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr is not getting init with default deleter

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;
});

The error:

/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;
                                                                ^

This is my compiler version:

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

The Animal and Cat classes are trivial. This is the entire code.

like image 366
chunkyguy Avatar asked Jul 28 '13 08:07

chunkyguy


People also ask

Does unique_ptr delete itself?

unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they themselves are destroyed, or as soon as their value changes either by an assignment operation or by an explicit call to unique_ptr::reset.

What does unique_ptr Reset do?

std::unique_ptr::resetDestroys the object currently managed by the unique_ptr (if any) and takes ownership of p. If p is a null pointer (such as a default-initialized pointer), the unique_ptr becomes empty, managing no object after the call.

What happens when unique_ptr goes out of scope?

unique_ptr. An​ unique_ptr has exclusive ownership of the object it points to and ​will destroy the object when the pointer goes out of scope.


1 Answers

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 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));
like image 138
Casey Avatar answered Oct 21 '22 20:10

Casey