Alex Peniz
Alex Peniz

Reputation: 483

Deallocating Template Objects on the Stack

Suppose I have a class that looks like the following:

#include <stdlib.h>
#include <stdio.h>

#include "entry.hpp"
#include "hashes.hpp"
using namespace std;

const double MAX_LOAD = 0.5;

template <typename K, typename V, typename H = GenericHash<K> >
class HashMap
{
    public:
        HashMap(size_t init_capacity){
            entries = new Entry<K, V> *[init_capacity];

            for(int i = 0; i < init_capacity; i++){
                entries[i] = NULL;
            }

            num_entries = 0;
            capacity = init_capacity;
        }
        ~HashMap(){
            for(int i = 0; i < capacity; i++){
                if(entries[i] == NULL){
                    continue;
                }
                delete entries[i];
            }
            delete entries;
        }

In a file called main.cpp, I allocate a Hashmap like the following:

HashMap<int, int, IntHash<int> > hmap(MEDIUM_SIZE);

This doesn't use dynamic memory allocation, but the actual code for HashMap does. When the function finishes, will the destructor for hmap be called? Or do I have to do something else in order to free the memory allocated by hmap?

Upvotes: 0

Views: 70

Answers (1)

0x5453
0x5453

Reputation: 13589

Yes. For objects with automatic storage duration (e.g. local variables in functions), the destructor is always called as soon as that object goes out of scope.

This is one fundamental piece of "RAII". This pattern is frequently used to create objects that "clean up after themselves." For example:

struct Resource {
    File file;
    Resource(std::string filename) : { file = open(filename); }
    ~Resource() { close(file); }
};

void foo() {
    // some code

    { // start a new scope
        Resource r{"path/to/file"};
        // some code using r
    } // r.file is automatically closed here because r has gone out of scope

    // some more code
}

Upvotes: 3

Related Questions