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

C++ 返回字符串和常量字符的函数中存在错误值*,c++,string,C++,String,我的程序中有这个函数 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();

我的程序中有这个函数

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;
}
const char*Graph::toChar(){
std::字符串str;
const char*toret;
str=“”;
for(vector::iterator it=pile.begin();it!=pile.end();it++){
str+=(*it)->toString();
}
toret=str.c_str();
返回托雷特;
}
然后我调试函数,直到我返回toret,所有功能都正常工作;线路。我按下step over,调试器将转到std::string str;行和所有字符串和字符变量变为“”,因此函数的最终返回为“”(无)

我做错了什么

*(it)->toString();在调试器执行*toret=str.c_str();*toret中的值是正确的


Thx

您在这里所做的是不好的:您正在返回
std::string
c_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;
}
const std::string Graph::toChar(){
std::字符串str;
for(vector::iterator it=pile.begin();it!=pile.end();it++){
str+=(*it)->toString();
}
返回str;
}

void图形::toChar(std::string&out){
out=“”
for(vector::iterator it=pile.begin();it!=pile.end();it++){
out+=(*it)->toString();
}
}

你在这里做的是不好的:你正在返回一个
std::string
c_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;
}
const std::string Graph::toChar(){
std::字符串str;
for(vector::iterator it=pile.begin();it!=pile.end();it++){
str+=(*it)->toString();
}
返回str;
}

void图形::toChar(std::string&out){
out=“”
for(vector::iterator it=pile.begin();it!=pile.end();it++){
out+=(*it)->toString();
}
}

为什么返回的是
char const*
而不是字符串?为什么返回的是
char const*
而不是字符串?为什么返回的是
char const*而不是字符串?我想返回char const*的可能重复,因为我想使用此函数调用另一个带有系统的程序(graph->toChar());所以,也许另一种解决方案是创建一个不会从函数中删除的const char*(str.c_str();)副本。我该怎么做?或者另一个更好的解决方案,例如,如果您使用我的第一个返回字符串的示例,您可以这样做:
system(graph->toChar().c_str())我想返回char const*,因为我想用这个函数调用另一个系统程序(graph->toChar());所以,也许另一种解决方案是创建一个不会从函数中删除的const char*(str.c_str();)副本。我该怎么做?或者另一个更好的解决方案,例如,如果您使用我的第一个返回字符串的示例,您可以这样做:
system(graph->toChar().c_str())