简体   繁体   中英

Inserting the data ,containing a pointer, to vector

I have a following class:

class Op
    {
    private:
        std::vector<std::string> m_operands;
        std::string m_op;
    public:
        Op(std::string op = "") : m_op(op){}
        std::string GenCode();
        void AddOperand(std::string& operand) ;
        std::vector<std::string> GetOperands() const { return m_operands; }
        std::string GetOp() const { return m_op; }
    };

The instances of the class are saved to std::vector<Op> m_movOpV ; Ie the following method adds a new op:

Op* AddMovOp()
{
    Op op("MovOp");
    m_movOpV.push_back(op);
    return &m_movOpV.back();
}

In addition I have defined :

typedef std::pair<std::string,Op*> Assignment;
std::vector<Assignment> m_proceduralAssign;

Thus,after adding the Op,I can generate an Assignment using the following function :

void AddAssignment(ModuleVCodeGen::Op* op,const std::string& lExp)
{
    Assignment assignment = (Assignment)std::make_pair(lExp,op);
    m_proceduralAssign.push_back(assignment);
}

The belowfollowing scenario generates a problem:

1.Op* op1 = AddMovOp();
2.op1->AddOperand("operand1");
3.AddAssign(op,"1");
4.Op* op2 = AddMovOp();

After performing the step 4. m_movOpV is updated correctly with new Op .But m_proceduralAssign has a junk data : The Assignment that already exists in m_proceduralAssign turns to have empty m_operands and bad pointer to m_op . And no new Assignment (which I tried to add) is added.

Can you please advise where the problem happens?And how to solve it?

You should revisit your design. A big problem I see with your code right now is that, references and pointers to vector objects are invalidated quite often (during push_backs and other operations), so by returning a pointer to the newly inserted item you are asking for trouble. If I were you I'd look into saving the index instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM