basic_ostringstream :: str悬空指针 [英] basic_ostringstream::str dangling pointer

查看:97
本文介绍了basic_ostringstream :: str悬空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Recently I found the bug in the following code:

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()(例如,在auto * ptr = out.str( ).c_str();)导致指针悬空。

This is explained by cppreference.com: the copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer.

我没有任何问题可以解决此错误,但是,我在其中有很多地方项目,如下所示:

I don't have any problem fixing this bug, however, I have many places in the projects, which look like this:

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
{}

此代码是否具有未定义的行为,例如第一个代码片段?

Does this code has undefined behavior, like the first code fragment?

推荐答案

否,消息是std :: string,因此您需要在此时获取char缓冲区的内容的副本。

No, message(s) is a std::string so you take a copy of the contents of the char buffer at that point.

临时函数将持续使用您调用的函数的范围-在这种情况下为构造函数。

The temporary lasts for the scope of the function you call it with - in this case the constructor.

这篇关于basic_ostringstream :: str悬空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆