函数返回字符串和常量字符*中的错误值

Bad value in function returning string and const char*

本文关键字:错误 字符 返回 字符串 常量 函数      更新时间:2023-10-16

我的程序中有这个函数

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;
}

然后我正在调试函数,一切正常,直到我返回 toret; 行。我按步进,调试器将转到 std::string str; 行,所有字符串和字符变量都变成 ",所以函数的最终返回是 "(什么都没有)。

我做错了什么?

*(it)->toString(); 工作正常,当调试器执行 *toret = str.c_str();* 时,toret 中的值是正确的。

感谢

您在这里所做的事情很糟糕:您正在返回一个std::stringc_str,该在超出范围时将被删除。 无论是否调试模式,这都意味着不可预测的行为。 实际上相当可预测 - 您的程序会崩溃:)

您应该返回 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();
    }
}