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

Viewed 1537

I have a class, the member variable is std::unique_ptr<double[]>. Initializing this variable is always done by 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. I do some research about similiar examples. But all of them are about new className(), not make_unique().

the verison of cpp is 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.

2 Answers

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.

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.

Related