My question is summed up pretty well with this code snippet:
struct T {
int* heapValue;
T(){
this->heapValue = new int[3]; // any dynamic size
}
~T(){
delete[] this->heapValue;
}
}
int main() {
int N = 5; // some value determined at runtime
T* array = new T[N];
for (int i = 0; i < N; i++)
{
T t = T(123, 456, args);
t.do_something();
array[i] = t;
} // uh oh, t is deconstructed! and array[i].heapValue is invalidated
int x = array[0].heapValue[0]; // segfault
}
I was able to solve this by creating T** array
instead and making each t
with new T(args)
, but then when it comes time to deallocate array
I need to loop through each element and delete it first before deleting the array itself. This is slow and inconvenient. Also, T**
looks like a 2-dimensional array which is potentially misleading.
The same issue occurs with std::vector<T>
and can be solved with the equally slow and inconvenient std::vector<T*>
.
Is there any way to create a dynamic array T*
such that the elements are not deconstructed right after being assigned?