将strstream转换为sstream冲突关于c_str()
Converting strstream to sstream conflict about c_str()
我有用strstream
编写的代码块。我将其转换为sstream
如下所示。我不确定,但我认为printStream->str()
返回一个字符串对象,其中包含 printStream
指向的流缓冲区中内容的副本(临时),然后您调用它c_str()
并得到一个const char *
,然后丢弃常量,然后返回函数范围之外的指针。 我认为由于它是您从printStream->str()
中获取的临时值,您将使用指向此函数外部已释放内存的指针。我应该怎么做?
char * FieldData::to_string() const
{
if(printStream)
return printStream->str();
FieldData* notConst = (FieldData*) this;
notConst->printStream = new std::ostrstream;
// check heap sr60315556
if (notConst->printStream == NULL)
return NULL;
*(notConst->printStream) << "Invalid Field Type";
*(notConst->printStream) << ' ';
return printStream->str();
}
char * FieldData::to_string() const
{
if(printStream)
return const_cast<char *>(printStream->str().c_str());
FieldData* notConst = (FieldData*) this;
notConst->printStream = new std::ostringstream;
// check heap sr60315556
if (notConst->printStream == NULL)
return NULL;
*(notConst->printStream) << "Invalid Field Type";
*(notConst->printStream) << ' ';
return const_cast<char *>(printStream->str().c_str());
}
将返回类型更改为 std::string
并直接返回std::string
对象。
我认为一个名为to_string
的函数真的,真的,真的应该返回一个std::string
。
然后所有这些垃圾都可以被替换为
std::string FieldData::to_string() const
{ return "Invalid Field Type"; }
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- c boost.python不能将const char*转换为str
- 从"char"到"const char*"的转换无效 [-fpermissive] str::atoi (字符串到整数)
- 无法将缓冲区 [200] 转换为 str[]
- Boost.Python.ArgumentError:Python str未转换为std::string
- 将 str 转换为字符*问题
- 将 STR 转换为 int 的简单方法?C++
- 使用 str.at(x) 将字符串转换为 int
- 将字符串转换为无符号字符 str
- 使用 c.str 从字符串转换为 cstring
- 转换str字符串以用于std::getline分隔符的字符串
- ATL如何转换BSTR* str到注册表项.SetValue(LPCTSTR字符串类型)
- 如何将c++str转换为int
- std::string 到 str::string.c_str() 与文件路径的转换中存在有趣的问题
- 将int类型的向量转换为str类型的向量