Reputation: 10153
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
;
I.e. 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?
Upvotes: 1
Views: 342
Reputation: 15916
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.
Upvotes: 2