I recently wrote a cpp file that I'm questioning. I'm unsure of whether the approach I took is correct or if it will cause damage to the heap.
The goal of the project is to be able to do "clean-up" on dynamically allocated memory by storing the created object in a static vector shared across the same classes.
The vector stores pointers, and unfortunately it doesn't seem as if clear or resize properly deletes or destructs the pointers stored in the vector so I'm manually doing it for each value in the vector. Is this the correct approach?
#include <iostream>
#include <vector>
class ManagedClass{
private:
static std::vector<ManagedClass*> track;
short index;
static short currentAmount;
public:
ManagedClass(){
track.push_back(this);
index = currentAmount++;
}
~ManagedClass(){
std::cout << "destructor called for-- " << index << std::endl;
currentAmount--;
if(currentAmount == 0){
std::cout << "Clearing the vector--" << std::endl;
std::vector<ManagedClass*> temp;
track = temp;
std::cout << "size of vector is now-- " << track.size() << std::endl;
currentAmount = 0;
}
}
static void showAll() {
std::vector<ManagedClass*>::iterator first = track.begin(), last = track.end();
while(first != last){
std::cout << static_cast<ManagedClass*>(*first) << " " << std::flush;
first++;
}
}
static void releaseAll(){
for(int i = track.size() + 1; i > 1; i--){
delete track[i - 2]; // is this safe?
}
}
};
std::vector<ManagedClass*> temp;
std::vector<ManagedClass*> ManagedClass::track = temp;
short ManagedClass::currentAmount = 0;
int main(){
new ManagedClass;
new ManagedClass;
new ManagedClass;
ManagedClass::showAll();
ManagedClass::releaseAll();
std::cin.get();
return 0;
}