Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't unique_ptr::reset have overloads that take a deleter?

Tags:

Is there a reason unique_ptr::reset doesn't have overloads that take a const deleter& and deleter&& to match its constructors that take those as a second argument?

The stored deleter in unique_ptr would be copy assigned or move assigned with the argument from reset. If the deleter is noncopyable or nonmovable, calling the corresponding overload of the reset wouldn't compile. This seems like it would be consistent behavior with the constructors.

like image 942
David Avatar asked Feb 06 '12 21:02

David


People also ask

Can you delete a unique_ptr?

An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.

What does unique_ptr reset method 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.

Does unique_ptr call destructor?

Yes. Well the unique ptr has a function object that by default invokes delete on the pointed to object, which calls the destructor. You can change the type of that default deleter to do almost anything.


1 Answers

I thought about adding that but you can get the equivalent functionality with a move assignment operator:

ptr = unique_ptr<T, D>(new T(another_value), D(another_state)); 

So I opted for not saying the same thing with reset in the interest of keeping the API reasonably small.

Update

And I live and learn...

The syntax can actually be much simpler than what I show above:

ptr = {new T(another_value), D(another_state)}; 
like image 136
Howard Hinnant Avatar answered Oct 13 '22 11:10

Howard Hinnant