basic_ostringstream::str悬挂指针



最近我在以下代码中发现了错误:

ostringstream o;
o << "some string";
const char* s = o.str().c_str(); // empty string instead of expected "some string"

cppreference.com对此进行了解释:str返回的底层字符串的副本是一个临时对象,它将在表达式结束时被销毁,因此直接对str()的结果调用c_str(;)导致指针悬空

我修复这个错误没有任何问题,然而,我在项目中有很多地方,看起来像这样:

ostringstream o;
o << "error description";
throw my_exception(o.str().c_str());
...
my_exception::my_exception(const char* s) :
    message(s)     // message is std::string
{}

这个代码是否有未定义的行为,就像第一个代码片段一样?

不,消息是std::字符串,所以您在这一点上复制了char缓冲区的内容。

临时持续到调用它的函数的作用域,在本例中为构造函数。

最新更新