Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to delete basic data types in a destructor? C++

If I have a class that looks something like this:

class SomeClass {
    public:
        SomeClass(int size) {
                     arr = new int[size];
                     someInt = size / 10;
                    };
        ~SomeClass() {
                      delete [] arr;
                      //do I need to somehow delete the int value 'someInt'?
                     };
    private:
        int *arr; //pointer to dynamically allocated array
        int someInt;
}

What, exactly, should be contained in the destructor to avoid memory leaks?

I am aware that I need to delete the array, since it is dynamically allocated, but do I need to do anything with int values, or other basic data types?

Thanks, Jonathan

like image 875
Jonathan Avatar asked Apr 18 '13 18:04

Jonathan


2 Answers

No.

But not just for basic types. For anything that you didn't allocate with new you don't have to call delete on. Even for pointers.

delete has (somehow) nothing to do with the member variable type. What matters is if you have allocated it (with new) in your constructor (or somewhere else in your class methods).

The rule of thumb is

Have as many delete as new
Have as many delete[] as new[].

Of course sometimes you will have to delete something you haven't allocated but are pointing to if it is not needed anymore (allocated by someone else but you are the only one using it).

Of course sometimes you will have to NOT delete something you HAVE allocated but someone else is pointing to (allocated by you but someone else is using it).

like image 109
stardust Avatar answered Nov 15 '22 19:11

stardust


No, you don't have to manually delete automatic variables. Only delete what you new.

Additionally, you can avoid the need to delete the array by using RAII via a smart pointer. Then you won't have to manually define a destructor; the automatically defined destructor will do what you need.

class SomeClass {
    public:
        SomeClass(int size)
          : arr {new int[size]}
          , someInt = size/10;
        {};

    private:
        std::unique_ptr<int[]> arr; //pointer to dynamically allocated array
        int someInt;
}

It's even better to use a more specialized type such as std::vector instead of a generic smart pointer:

class SomeClass {
    public:
        SomeClass(int size)
          : arr (size)
          , someInt = size/10;
        {};

    private:
        std::vector<int> arr;
        int someInt;
}
like image 33
bames53 Avatar answered Nov 15 '22 19:11

bames53