I'm building a Java-like ArrayList class in C++ just for practice (yes, I know std::vector and other great alternatives exist).
I understand that the new keyword is paired with the delete keyword and malloc, calloc, realloc is paired with free.
So, let's say I have a class ArrayList that contains pointers to some generic type T. In other words, the underlying array in my ArrayList looks like this
T* array where T is some template <typename T>.
I'm defining my destructor for ArrayList and I have a few questions..
The destructor should be responsible for freeing all the memory stored in the
ArrayList. But I don't know if theT*s that it's holding were created using anewor amalloc-type, so how do I dealloc them? I feel like running into this problem is a sign of an anti-pattern, so any advice would be appreciated!The
ArrayListitself can be instantiated in two ways
On the stack...
ArrayList arr;
or on the heap...
ArrayList arr = new ArrayList();
If it was initialized on the stack, I don't have to worry about managing arr's memory, but can I assume that its destructor will be called before the arr itself is somehow deallocated?
If it was initialized on the heap, does calling delete arr call its destructor and deallocate arr itself?
Thank you!