Chromz
Chromz

Reputation: 183

c++ - How to implement a destructor of an object that uses itself in the constructor

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?

Upvotes: 1

Views: 115

Answers (2)

Martin
Martin

Reputation: 59

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;
  ...
};

Upvotes: 0

gsamaras
gsamaras

Reputation: 73366

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.

Upvotes: 1

Related Questions