Reputation: 3025
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?
Upvotes: 3
Views: 2049
Reputation: 361442
for (int i = 0; i < 4; i++)
{
string label = prefix + classname + "." + methodname[i];
names.push_back(label.c_str()); //what you're pushing? a temporary!
} //<--- `label` is destroyed here and it's memory is freed.
Here label
is a variable which gets destroyed at the closing brace and gets created again, in each iteration.
That means, what you're pushing to names
is a temporary value. That is causing the problem.
I would suggest you to use this:
std::deque<std::string> names;
then do this:
names.push_back(label); //a copy is pushed to the deque!
Upvotes: 9
Reputation: 13510
this is because the string label
is a temporary, and its chhar pointer isn't valid once it exit the scope - the for loop, in this case.
I suggest to use deque<string>
instead. this way you can push label
itself, and then a real copy of label
will be created inside the deque.
Upvotes: 0