I am writing a compiler and use deque to store methods labels of a class and here’s the sample code:
#include <deque>
#include <iostream>
#include <string>
using std::cout;
using std::deque;
using std::endl;
using std::string;
int main()
{
deque<const char *> names;
string prefix = "___";
const char *classname = "Point";
const char *methodname[] = {"Init", "PrintBoth", "PrintSelf", "equals"};
for (int i = 0; i < 4; i++)
{
string label = prefix + classname + "." + methodname[i];
names.push_back(label.c_str());
}
for (int i = 0; i < 4; i++)
cout << names[i] << endl;
return 0;
}
However, the result is not what I’ve expected:
___Point
___Point.PrintSelf
___Point.PrintSelf
___Point.equals
Also, I noticed if I simply push back the methodname
names.push_back(methodname[i])
I get all the methodnames in order.
What have I done wrong here?
Here
labelis a variable which gets destroyed at the closing brace and gets created again, in each iteration.That means, what you’re pushing to
namesis a temporary value. That is causing the problem.I would suggest you to use this:
then do this: