Search code examples
c++shared-ptrnfa

shared_ptr compiler error invalid conversion


I have a class called State which has a shared_ptr, weak_ptr and a int as its fields. I also have another class called Automata which has a shared_ptr to a state. I am using State to mimic a state in NFA. The Automata is a linked list of states in an NFA. And states are linked with shared_ptr, self loop is indicated by weak_ptr.

class State {
    public:
        // ptr to next state
        std::shared_ptr<State> nextState;
        // ptr to self
        std::weak_ptr<State> selfLoop;
        // char
        int regex;
       // Constructor
       State(const int c) : regex(c){}
       // Destructor
       ~State();
};
#define START 256

#define FINAL 257

class Automata {
    private:
       std::shared_ptr<State> start;
    public:
       // Constructor, string should not be empty
       Automata(const std::string &str);
      // Destructor
      ~Automata();
      // Determine a string matched regex
      bool match(const std::string &str);
};

The constructor of Automata basically takes in a regex and convert it into an NFA.(It works! See this if you are interested: https://swtch.com/~rsc/regexp/regexp1.html)

The compiler error happens when compiling Automata's constructor. It is implemented as follows

Automata::Automata(const string &str) {
    start = make_shared<State>(new State(START)); // Error is here, START defined above
    for (loop traversing str) {
        //add more states to start
    }
}

I got an error that states

// A lot gibbrish above
Automata.cc:7:45:   required from here
/usr/include/c++/4.8/ext/new_allocator.h:120:4: error: invalid conversion
from ‘State*’ to ‘int’ [-fpermissive]
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
^
 In file included from Automata.h:4:0,
                  from Automata.cc:2:
 State.h:18:2: error:   initializing argument 1 of ‘State::State(int)’ [-fpermissive]
 State(const int c);
 ^

Not sure what I did wrong. I am totally new to shared_ptr, so I have no idea if it's the problem of make_shared or error with State constructor? Can you help me fix this?


Solution

  • Didn't you want to write:

    Automata::Automata(const string &str) {
        start = make_shared<State>(START); // make_shared will call new internally
        for (loop traversing str) {
            //add more states to start
        }
    }
    

    ?