2017-10-20 15 views
0

我有这样的代码块,写成strstream。我将它转换为sstream如下。我不确定,但我认为printStream->str()正在返回一个字符串对象,其中包含printStream所指向的流缓冲区中的内容的副本(临时),然后您将调用c_str()并获取const char *,然后投射该常量,然后将该指针返回到函数作用域之外。我认为,因为您从printStream->str()得到的临时值,您将使用一个指针来释放此函数之外的内存。我应该怎么做?将strstream转换为关于c_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) << '\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()); 
} 
+1

不要使用'new',不使用C-风格的转换,不要使用'const_cast' *特别*修改变量,不要使用C风格的字符串,不要返回指向已经释放的内存的指针。事实上,我相当确定,如果重新开始比修复此代码更容易。例如 – milleniumbug

+0

我应该如何更改我的代码?返回const_cast (printStream-> str()。c_str()); –

回答

1

更改返回类型std::string并直接返回std::string对象。

+0

我该怎么办?例如,我怎样才能改变这一行 return const_cast (printStream-> str()。c_str()); –

1

我觉得一个叫to_string的功能真的,真的,真的应该会返回一个std::string

然后所有这些垃圾可以通过

更换
std::string FieldData::to_string() const 
{ return "Invalid Field Type"; }