函数返回字符串和常量字符*中的错误值
Bad value in function returning string and const char*
我的程序中有这个函数
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::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;
}
或
void Graph::toChar(std::string &out) {
out = ""
for (vector<Edge*>::iterator it = pile.begin(); it != pile.end(); it++) {
out += (*it)->toString();
}
}
相关文章:
- 我的字符计数代码计算错误.为什么
- 错误:字符数组的初始值设定项太多
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- 在函数 strcpy() 中访问字符数组时出现分段错误
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 为什么我的代码在尝试复制字符数组时引发 C6386 错误?
- 为什么C++在将浮点数转换为字符时没有显示缩小转换错误?
- C++ 字符错误
- 增量生成 - 错误:字符串的第一个字符应'0'或'1'
- 我如何处理有关输入的字符串大小超过字符数组设置大小的错误?
- C++错误字符分配
- C 字符串对象错误字符
- 奇怪的错误字符加密 (ASCII)
- 将 XOR 加密错误字符转换为 int 会失去精度
- 错误:字符数组的初始化器字符串太长c++
- 文件输出中存在错误字符
- 我使用 POCO 解析 JSON.它抛出一个异常:JSON 异常:错误字符.如何处理汉字
- 返回错误字符的c++数组
- c++凯撒密码程序执行错误字符