Skip to content

Instantly share code, notes, and snippets.

@emmanuj
Created November 18, 2015 01:24
Show Gist options
  • Save emmanuj/a52688710338e3e61465 to your computer and use it in GitHub Desktop.
Save emmanuj/a52688710338e3e61465 to your computer and use it in GitHub Desktop.
// ===== Deleting pointers in a container.
//To delete a dynamically allocated pointer in c++
delete ptr;
// To delete pointers in a vector e.g
std::vector<Frame*> frames; //previously created vector
for ( unsigned int i = 0; i < frames.size(); ++i ) {
delete frames[i]; // ExplodingSprite made them, so it deletes them
}
// Delete from a map of pointers
std::map<std::string, Frame*>::iterator frame = frames.begin();
while ( frame != frames.end() ) {
delete frame->second;
++frame;
}
// Deleting from a map of vectors is similar. Iterate through the map, iterate through each vector in map and call delete
std::map<std::string, std::vector<Frame*> >::iterator frames = multiFrames.begin();
while ( frames != multiFrames.end() ) {
for (unsigned int i = 0; i < frames->second.size(); ++i) {
delete frames->second[i];
}
++frames;
}
// Hope you get the idea. Basically loop through the container and delete the pointer.
// The idea is the same for lists and other containers.
// Also for this to work successfully, ensure that the class that you are deleting overrides a destructor.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment