本文介绍了什么时候std :: unique_ptr< A>如果A有析构函数,需要一个特殊的删除器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 unique_ptr< A> 中的类 A 是它自己的析构函数,是否有必要声明一个删除器以确保唯一指针使用该析构函数?我想到的示例是 A 的成员 mx 类型为 user_matrix (我刚刚写的一个名字),它需要调用一个函数 free(...)来释放它的内存,一个就可以定义

If the class A in unique_ptr<A> it's own destructor, is it necessary to declare a deleter to ensure that the unique pointer uses that destructor? The example I am thinking of is that A has a member mx of type user_matrix (a name I just made up) which needs to call a function free(...) to release its memory, one would define

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

由于 default_deleter<> 将调用 delete ,据我了解,应使用〜A()。但是,Josuttis(C ++ Standard Library:A Tutorial and Reference)一书中第5.2节关联资源的删除下打开和关闭目录的示例表明,可能需要声明一个特殊的删除器才能执行这,所以我很困惑....这是因为在给定的示例中,类 DIR 没有使用 closedir的析构函数(...)

Since default_deleter<> will call delete, it is my understanding that that should use ~A(). However, the example with the opening and closing of directories in Section 5.2, under "Deleters for Associated resources", of the book of Josuttis (The C++ Standard Library: A Tutorial and Reference) suggests one may need to declare a special deleter to do this, so I am confused.... Is this because, in the given example, the class DIR doesn't have a destructor that uses closedir(...)?

推荐答案

std的默认删除器: :unique_ptr< T> 将调用 delete 和默认删除器 std :: unique_ptr< T []> 将调用 delete [] ,而那些将适当地调用对象的析构函数。

The default deleter of std::unique_ptr<T> will call delete and the default deleter of std::unique_ptr<T[]> will call delete[] and those will call the destructors of the objects appropriately.

可能发生的事情是,需要在销毁之前立即安排操作,这是因为析构函数不完整(或缺少),或者是因为 you 想要做更多的事情(例如,进行一些日志记录)。 在这种情况下,您需要一个专用的删除器来实现此目的。

What may happen is that an operation need be scheduled right before the destruction, either because the destructor is incomplete (or lacking) or because you would like to do something more (for example, some logging). In this case you need a dedicated deleter to achieve this.

例如,假设您有一个句柄 em>,例如 FILE * (在C中常见)。这些句柄通常带有某种 close 方法,并且没有析构函数(因为C中没有析构函数)。

Suppose, for example, that you are given a handle, such as FILE* (common in C). Those handles often come with a close method of some sort and no destructor (because there is none in C).

struct FileCloser {
    void operator()(FILE* f) { if (f) { fclose(f); } }
};

UniqueFile = std::unique_ptr<FILE, FileCloser>;

这篇关于什么时候std :: unique_ptr&lt; A&gt;如果A有析构函数,需要一个特殊的删除器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 00:29