我正在编写一个编译器,并使用deque来存储类的方法标签,下面是示例代码:
#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;
}然而,结果并不是我所期望的:
___Point
___Point.PrintSelf
___Point.PrintSelf
___Point.equals另外,我注意到如果我简单地将方法名
names.push_back(methodname[i])我把所有的方法名都整理好了。
我在这里做错了什么?
发布于 2012-05-11 22:29:26
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.在这里,label是一个变量,它在结束的大括号处被销毁,然后在每次迭代中重新创建。
这意味着,您推送到names的是一个临时值。这就是导致问题的原因。
我建议你使用这个:
std::deque<std::string> names;然后执行以下操作:
names.push_back(label); //a copy is pushed to the deque!发布于 2012-05-11 22:31:50
这是因为string label是临时的,一旦它退出作用域--在本例中是for循环--它的chhar指针就无效了。
我建议改用deque<string>。这样,您可以推送label本身,然后将在the中创建一个真正的label副本。
https://stackoverflow.com/questions/10553268
复制相似问题