Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the custom deleter of std::unique_ptr work?

According to N3290, std::unique_ptr accepts a deleter argument in its constructor.

However, I can't get that to work with Visual C++ 10.0 or MinGW g++ 4.4.1 in Windows, nor with g++ 4.6.1 in Ubuntu.

I therefore fear that my understanding of it is incomplete or wrong. I can't see the point of a deleter argument that's apparently ignored, so can anyone provide a working example?

Preferably I'd like to see also how that works for unique_ptr<Base> p = unique_ptr<Derived>( new Derived ).

Possibly with some wording from the standard to back up the example, i.e. that with whatever compiler you're using, it actually does what it's supposed to do?

like image 422
Cheers and hth. - Alf Avatar asked Nov 25 '11 21:11

Cheers and hth. - Alf


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.

Can unique_ptr be copied?

A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.

What is std :: unique_ptr?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

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.


1 Answers

This works for me in MSVC10

int x = 5; auto del = [](int * p) { std::cout << "Deleting x, value is : " << *p; }; std::unique_ptr<int, decltype(del)> px(&x, del); 

And on gcc 4.5, here

I'll skip going to the standard, unless you don't think that example is doing exactly what you'd expect it to do.

like image 120
Benjamin Lindley Avatar answered Sep 22 '22 10:09

Benjamin Lindley