问题描述
我有这个用strstream
编写的代码块.然后将其转换为sstream
,如下所示.我不确定,但是我认为printStream->str()
返回的是一个字符串对象,该对象带有printStream
所指向的流缓冲区中的内容的副本(临时),然后您在其上调用c_str()
并得到一个const char *
,然后放弃常量性,然后将指针返回到函数作用域之外.我认为由于您是从printStream->str()
返回的临时值,因此将使用指针在该函数之外分配内存.我该怎么办?
I have this code block as written with strstream
. And I converted it to sstream
as below. I'm not sure, but I think printStream->str()
is returning a string object with a copy (temporary) of the contents in the stream buffer pointed by printStream
, and then then you are invoking c_str()
on it and getting a const char *
, and then casting away the const-ness, and then returning the pointer outside the function scope. I think since its a temporary value you are getting back from printStream->str()
, you will be using a pointer to deallocated memory outside this function. How should I do this?
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) << '\0';
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) << '\0';
return const_cast<char *>(printStream->str().c_str());
}
推荐答案
我认为一个叫做to_string
的函数真的,真的, really 应该返回一个std::string
.
I think a function called to_string
really, really, really should return a std::string
.
然后所有这些垃圾都可以替换为
And then all this junk can be replaced by
std::string FieldData::to_string() const
{ return "Invalid Field Type"; }
这篇关于关于c_str()将strstream转换为sstream冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!