c++ - Where do I delete objects? I'm out of scope -
from have gathered it's imperative delete has been allocated new. having said feel i'm out of scope in program able access & delete objects.
gamestatestack.h
#include <iostream> class node { public: std::string gamestate; node * nextgamestate; }; class gamestatestack { private: node * _topstate; void destory(); public: int gamestatescount; void pushgamestate(std::string element); void popgamestate(); std::string currentgamestate(); gamestatestack(); ~gamestatestack(); }; extern gamestatestack state;
gamestatestack.cpp
gamestatestack state; gamestatestack::gamestatestack() { _topstate = null; gamestatescount = 0; } gamestatestack::~gamestatestack() { } void gamestatestack::pushgamestate(std::string gamestatename) { node *newtopstate = new node; // local variable if (_topstate == null) { // statements } else { // statements } } void gamestatestack::popgamestate() { if (_topstate == null) std::cout << "error: no gamestates available pop"; else { node * old = _topstate; // local variable // statements } } std::string gamestatestack::currentgamestate() { node *temp; // local variable // statements } void gamestatestack::destory() { node *abc; // created variable access _topstate variable , delete delete _topstate; delete abc->nextgamestate; delete abc; // , deleted abc. }
you can read comments , see i've posted local variable can't access in destructor hence cannot delete those. if try deleting them using delete keyword in own scope stack i've implemented stop working. hence not know how , delete these objects!
"hence not know how , delete these objects!"
the best solution rid of calling delete
@ all, leave appropriate smart pointer, e.g.
class node { public: std::string gamestate; std::unique_ptr<node> nextgamestate; };
and other pointer types accordingly.
Comments
Post a Comment