dimanche 6 août 2017

Invalid free when using unique_ptr

I need some help here about unique pointers in C++11. I have written a simple state machine. This is only an excerpt of the code but that should do it to understand. The problem is the vector containing a unique pointer. After calling the add state routine I get an invalid free error. What is wrong with inserting a into the vector? Replacing unique_ptr with shared_ptr works fine. When there is no solution, using shared_ptr would be an option but I want to understand the problem.

template<class TBaseState>
struct TokenizerContainer {
    std::vector<std::unique_ptr<TBaseState>>     states;
    std::unordered_map<std::string, TBaseState*> tokens;

    template<class TMachine, class TState>
    TState *addState(const std::string &token){
        TState *state = new TState;
        states.push_back(std::unique_ptr<TState>(state));

        for(unsigned int i = 1;i < token.size() - 1;++i) {
            tokens.insert(std::make_pair(token.substr(0, i), nullptr));
        }

        tokens.insert(std::make_pair(token.substr(0, token.size() - 1), state));
        return state;
    }
};

Aucun commentaire:

Enregistrer un commentaire