Search code examples
c++inheritancememory-leaksvirtual-destructor

Why isn't this a memory leak? Or is it? Deleting base class pointer without virtual destructors


I've been meddling around, testing for memory leaks with Intel Inspector, when I noticed something that should not be. I inherit from std::vector which is not supposed to have a virtual destructor, I have an extra member in the derived class, I do dynamic memory allocation on it, in main I create a derived class on the heap, cast to base class, call delete... and no memory leak is detected??? By all logic, I should get a memory leak.

template <typename T>
class DynamicArray : public std::vector<T> {
public:    
    DynamicArray() : children(nullptr) {
        children = new int(50);
    }
    ~DynamicArray() {
        if (children) delete children;
    }
    DynamicArray& operator<<(const T& value)
    {
        push_back(value);
        return *this;
    }
private:
    int *children;
};


int main() {
    DynamicArray<int> *pArray = new DynamicArray<int>;
    (*pArray) << 4 << 5;
    static_cast<std::vector<int>*>(pArray);
    delete pArray;
}

Solution

  • pArray is still of type DynamicArray<int> and wiil call the right destructor, this would likely leak:

    std::vector<int>* wrong = static_cast<std::vector<int>*>(pArray);
    delete wrong;
    

    edit: as Ben Voigt correctly mentioned, this last code snippet actually undefined behavior since the destructor of std::vector is not virtual. So it is not even guaranteed that this will leak