When does std :: unique_ptr <a> need a special debiter if A has a destructor?

If class A in unique_ptr<A> belongs to its own destructor, is it necessary to declare a debiter to make sure that the unique pointer uses this destructor? The example I'm thinking of is that A has a mx member of type user_matrix (the name I just made up) that needs to call the free(...) function to release its memory, one could define

 ~A(){ user_matrix::free(mx); /*etc*/} 

Since default_deleter<> will call delete , I understand that this should use ~A() . However, the example of opening and closing directories in section 5.2 in the "Deleters for Associated resources" section of the Josuttis book (C ++ Standard Library: Tutorial and Reference) suggests that you may need to declare a special deleter for this, so I confused .... Is it because in this example the DIR class does not have a destructor that uses closedir(...) ?

+4
source share
1 answer

The default debugger std::unique_ptr<T> will call delete , and the default destructor std::unique_ptr<T[]> will call delete[] , and they will accordingly call the object destructors.

What can happen, since the operation must be scheduled immediately before destruction, either because the destructor is incomplete (or missing), or because you want to do something else (for example, some logging). In this case, to achieve this you will need a dedicated debiter.

Suppose, for example, that you are given a handle, for example FILE* (common in C). These descriptors often have a close method of some kind and no destructor (because in C there is none).

 struct FileCloser { void operator()(FILE* f) { if (f) { fclose(f); } } }; UniqueFile = std::unique_ptr<FILE, FileCloser>; 
+11
source

Source: https://habr.com/ru/post/1493126/


All Articles