【问题标题】:Converting strstream to sstream conflict about c_str()将 strstream 转换为关于 c_str() 的 sstream 冲突
【发布时间】:2017-10-20 09:27:35
【问题描述】:

我有这个用strstream 编写的代码块。我将其转换为sstream,如下所示。我不确定,但我认为printStream->str() 正在返回一个字符串对象,其中包含printStream 指向的流缓冲区中内容的副本(临时),然后您在其上调用c_str() 并获得一个const char *,然后抛弃 const-ness,然后在函数范围之外返回指针。我认为由于它是您从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) << '\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());
}

【问题讨论】:

  • 不要使用new,不要使用C风格的强制转换,不要使用const_cast 尤其是来修改变量,不要使用C -style 字符串,不要返回指向已释放内存的指针。事实上,我很确定重新开始是否比修复此代码更容易。
  • 例如我应该如何更改我的代码? return const_cast(printStream->str().c_str());

标签: c++ compiler-errors sstream c-str strstream


【解决方案1】:

将返回类型改为std::string,直接返回std::string对象。

【讨论】:

  • 我该怎么办?例如,如何更改此行 return const_cast(printStream->str().c_str());
【解决方案2】:

我认为一个名为to_string 的函数真的,真的,真的应该返回一个std::string

然后所有这些垃圾都可以替换为

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 2014-07-03
    • 2018-01-28
    • 1970-01-01
    • 2015-07-04
    • 2019-08-15
    相关资源
    最近更新 更多