I'm trying to make the Thompson's construction algorithm in c++ (I'm somewhat new to the language). But I'm having some difficulties on implementing a destructor for my class NFiniteAutomaton. In some part of the constructor of NFiniteAutomaton I have:
NFiniteAutomaton() = default; NFiniteAutomaton(std::string regex){ // A lot of code here // .... NFiniteAutomaton single_ele; single_ele.init_state = new State; single_ele.final_state = new State; // A lot of code here // .... } Then in other parts of my code, I create pointers to single_ele.init_state's and single_ele.final_state's content in the main NFiniteAutomaton, because I want to reuse states instead of creating new ones with the same attributes. The struct State looks like this:
struct State; struct Transition { State* to; std::string symbol; }; struct State{ std::vector<Transition> transitions; }; So when I implement a destructor of NFiniteAutomaton that deletes all structs allocated on the heap, my problem is generated, because when single_ele gets out of the scope, it deletes all State pointers including the ones that other automata are using (because destructor gets called). One solution that I thought is to make a method Clear() that deletes all pointers whenever I want, and leave the default destructor. There is a way to implement the destructor of this class only using raw pointers?
NFiniteAutomaton. To me, automata should be self contained and fully encapsulated, never sharing states with anything else. Obviously not the case here.