0
template<>
class CalcHashClass<const char*> {
public:
    CalcHashClass(const char* v) {
        _v = new char[strlen(v) + 1];
        strcpy(_v,v);
    }

    ~CalcHashClass() {
        delete [] _v;
    }

    int hashCode() {
        printf("This is 'template <> class CalcHashClass<const char*>'.\n");
        int len = strlen(_v);
        int code = 0;
        for (int i = 0; i < len; ++i)
            code += (int)_v[i];
        return code;
    }

private:
    char* _v;
};

For above code, I am not sure what delete [] _v; mean? In my understanding, _v is a pointer. And to delete it should use delet _v, am I right? What does the [] mean?

Tom Xue
  • 3,149
  • 6
  • 38
  • 65

4 Answers4

4

delete x will only delete the variable x whereas the [ ] indicate to the memory manager that an array was allocated. delete[] x will delete the allocated array.

Suvarna Pattayil
  • 5,037
  • 5
  • 31
  • 58
3

Look at how the object that _v points to was allocated:

_v = new char[strlen(v) + 1];

It uses the new char[...] syntax, meaning that it is dynamically allocating an array of char. To destroy a dynamically allocated array, you need to use delete[].

The reason that this is necessary is because the compiler cannot tell that _v is pointing at an array from the type of _v alone. Since _v is just a char*, there's no reason you couldn't point it at a single dynamically allocate char. So delete[] tells the compiler that it needs to find out exactly how much space was allocated here and then deallocate all of it.

Joseph Mansfield
  • 104,685
  • 19
  • 232
  • 315
1

delete[] is called the "array delete operator". It deletes an array allocated using new[].

It is important to note that it is not allowed to use array delete with non-array new and vice versa.

For more information, see Why do we even need the "delete[]" operator?

As a side note, your class violates the Rule of Three. You should provide (or disable) the copy constructor and copy assignment operator.

Community
  • 1
  • 1
NPE
  • 464,258
  • 100
  • 912
  • 987
1

When you have an array allocated using new [] you need to use delete [] if you use just delete with memory allocated using new [] you will have undefined behavior. In the code posted you are allocating using new [] in your constructor here:

_v = new char[strlen(v) + 1];

hence the call to delete [] later on in the destructor.

Shafik Yaghmour
  • 148,593
  • 36
  • 425
  • 712