简体   繁体   English

如何使用unique_ptr为类设置析构函数 <double[]> 。 该实例由make_unique()创建

[英]How to set destructor for a class with unique_ptr<double[]>. the instance is created by make_unique()

I have a class, the member variable is std::unique_ptr<double[]> . 我有一个类,成员变量为std::unique_ptr<double[]> Initializing this variable is always done by make_unique<double[]>(size) . 始终通过make_unique<double[]>(size)初始化此变量。 But I do not know how to write code for destructor for this member variable 但是我不知道如何为该成员变量的析构函数编写代码

I know std::unique_ptr has a method get_deleter() , but when I look at the docs, it just provide self-defined delete. 我知道std::unique_ptr有一个方法get_deleter() ,但是当我看文档时,它只是提供了自定义删除。 I do some research about similiar examples. 我对类似示例进行了一些研究。 But all of them are about new className() , not make_unique() . 但是所有这些都是关于新的className() ,而不是make_unique()

the verison of cpp is c++17 cpp的版本是c ++ 17

My code 我的密码

class test{
public:
     test(int size) : size_{size}, arr_{make_unique<double[]>( size )} {}

     ~test(){
         // how to destroy arr_
     }
private:
    int size_;

    std::unique_ptr<double[]> arr_;
};

I do not know how to start. 我不知道如何开始。 I know there is a keyword delete , but I think it is not useful in this case. 我知道有一个关键字delete ,但是我认为在这种情况下它没有用。

Do not write a destructor at all. 根本不要编写析构函数。

std::unique_ptr will do the cleanup for you correctly, and indeed that's the main point of using a unique_ptr in the first place. std::unique_ptr将正确地为您进行清理,实际上这是首先使用unique_ptr要点。

Whenever possible, follow the Rule Of Zero : Use smart pointers and containers correctly, and don't declare any destructor, copy constructor, move constructor, copy assignment, or move assignment. 只要有可能,请遵循零规则 :正确使用智能指针和容器,不要声明任何析构函数,复制构造函数,移动构造函数,复制分配或移动分配。 (See the link for discussion of the main exception, declaring an interface's destructor virtual, and deleting or defaulting the rest.) (有关主要异常的讨论,请参见链接,声明接口的析构函数是虚拟的,其余部分则删除或默认。)

I do not know how to write code for destructor for this member variable 我不知道如何为此成员变量的析构函数编写代码

Nothing in particular needs to be written in order to destroy any member variable. 为了销毁任何成员变量,无需特别编写任何内容。 All member objects as well as base class objects are destroyed by all destructors after the body of the destructor has been executed. 在执行析构函数的主体之后,所有析构函数都将销毁所有成员对象以及基类对象。

There is no need to do anything in the body of the destructor, and therefore the implicitly generated destructor is sufficient for the class. 不需要在析构函数的主体中做任何事情,因此隐式生成的析构函数对于该类就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM