1

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?

1
  • I think there needs to be more concrete examples of what you're doing with NFiniteAutomaton. To me, automata should be self contained and fully encapsulated, never sharing states with anything else. Obviously not the case here. Commented Sep 16, 2017 at 7:16

2 Answers 2

1

One solution that I thought is to make a method Clear() that deletes all pointers whenever I want, and leave the default destructor.

Possible but why create a new function that the user of the class should be aware of instead of making the destructor take care of de-allocating dynamic memory? I wouldn't do that.

You should set your pointers to nullptr, before the destructor of NFiniteAutomaton is called. In the destructor use delete for init and final state.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know deleting a nullptr was safe. Thanks a lot.
0

If you want to make single_ele object persistent outside the constructor, define it as a class property rather than as a local object. The destructor can do its normal cleanup (no need for Clear() function), and the object will call the destructor only at the end of your program.

class NFIniteAutomaton { protected: static NFIniteAutomaton single_ele; ... }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.