I want to be sure that no memory leak takes place.
struct tStruct{
uint32_t id;
A* a;
C b;
};
std::vector<tStruct*> m_vector;
I push and erase objects into vector following way.
Pushing :
tStruct* myStruct = new tStruct;
myStruct->id = ID; // Some unique value
myStruct->a= new A();
myStruct->b = c; // c is an object
m_vector.push_back(myStruct);
Erasing :
// Some stuff here
for (uint32_t i = 0; i < m_vector.size(); i++) {
if (m_vector.at(i)->id == ID) { // Some filtering
delete m_vector.at(i);
m_vector.erase(m_vector.begin() + i);
}
}
Do i understand correctly that
- I need to delete myStruct->a explicitely as it is alloced in heap ?
- For the other members, they will be deleted automatically as they are in stack.
You need to manually delete all dynamically allocated objects which are created by
new operator. Otherwise you have potential memory leak, as you haven’t deletedA* a;newanddelete,new []anddelete []should always be used in pair.Better solution is to use smart pointers:
Use erase remove idiom to remove items from vector: