我的程序里有这个函数
const char* Graph::toChar() {
std::string str;
const char* toret;
str = "";
for (vector<Edge*>::iterator it = pile.begin(); it != pile.end(); it++) {
str += (*it)->toString();
}
toret = str.c_str();
return toret;
}
然后我调试函数一切正常,直到我进入 return toret; 行。我按下 step over,调试器将转到 std::string str; 行,所有字符串和字符变量都变成 "",所以函数的最终返回是 < em>""(无)。
我做错了什么?
*(it)->toString(); 正常工作,当调试器执行 *toret = str.c_str();* toret 中的值是正确。
谢谢
最佳答案
你在这里做的事情很糟糕:你正在返回 std::string
的 c_str
,当它超出范围时将被删除。无论 Debug模式与否,这都意味着不可预测的行为。实际上相当可预测 - 你的程序会崩溃 :)
您应该返回 const std::string
,接受 std:string &
作为参数并构建它,或者使用 strdup()
将字符串的 c_str 复制到内存中。请记住,使用 strdup() 意味着您必须稍后将其删除。
这里有两种形式的函数可以工作:
const std::string Graph::toChar() {
std::string str;
for (vector<Edge*>::iterator it = pile.begin(); it != pile.end(); it++) {
str += (*it)->toString();
}
return str;
}
或
void Graph::toChar(std::string &out) {
out = ""
for (vector<Edge*>::iterator it = pile.begin(); it != pile.end(); it++) {
out += (*it)->toString();
}
}
关于c++ - 函数返回字符串和 const char* 中的错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10153442/