Deleting a struct that has a class member

72 Views Asked by At

I have a struct:

struct holder
{
    int val;
    std::unordered_map<int, int> num_to_addr;
};

I dynamically allocate a struct holder:

struct holder* handle = new struct holder;

I do work and then want to deallocate it:

delete handle;

My question is, will the unordered_map inside of handle be destructed as well?

I have production code running that uses the code above, the program has a memory leak that has gone unfound for days. I am wondering if that could be what is causing the memory leak, because this code is ran only a few times, and the leak is also intermittent, so this may be it but nobody knows exactly.

1

There are 1 best solutions below

0
Chris On

Yes, the map's destructor will be invoked by the auto-generated destructor for holder. Now, if num_to_addr had been dynamically allocated, and not using a smart pointer like std::unique_ptr then you'd want to write a destructor that explicitly deletes it.

E.g.

struct holder {
    int val;
    std::unordered_map<int, int> *num_to_addr;

    // a bunch of constructors and copy assignment 
    // operators and such...

    ~holder() {
        delete num_to_address;
    }
};

You would also want to read up on the rule of three/five/zero.