c++ - 我可以安全地从 c++ 中的 std::stringstream 中获取 c_str 吗?

标签 c++ reference pass-by-reference lifetime

我正在使用一个 C 函数,它接受一个字符串(即指向以 null 结尾的 char 数组的指针)并在内部对其进行处理。但是,它不会在函数返回后保留对字符串的引用。

我想向它传递一些格式化的输入,所以我使用 std::stringstream。为了保持我的代码更清晰——并且因为这种模式在整个代码库中重复,我想简单地传递 ss.str().c_str()

对我来说,这看起来很可怕,因为我正在调用临时 ss.str() 上的方法,但我认为由于生命周期延长,这没关系。即,该标准规定:

A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call [...] In all these cases, the temporaries created during the evaluation of the expression initializing the reference, except the temporary to which the reference is bound, are destroyed at the end of the full-expression in which they are created and in the reverse order of the completion of their construction.

(强调我的)

因此,我希望我的值能够一直保留到 C API 调用结束。我错了吗?这样做安全吗?从概念上讲,我的代码如下所示:

void g(int x, int y) {
    std::stringstream ss;
    ss << "(" << x << ", " << y << ")";
    puts(ss.str().c_str());
}

最佳答案

是的,没问题,并且在使用 C 风格 API 时经常会出现 ss.str().c_str()

通俗地说,从 ss.str() 返回的匿名临时 std::stringputs() 函数调用后仍然存在。这意味着 c_str() 返回的 const char* 指针在 puts() 期间保持有效。

不能做的是:

const char* ub = ss.str().c_str();
puts(ub);

因为指针 ub 悬空。

关于c++ - 我可以安全地从 c++ 中的 std::stringstream 中获取 c_str 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65566294/

相关文章:

c++ - 为什么可以只给一个接受引用的函数一个对象(而不是一个引用)?是否自动生成引用?

reference - 我什么时候应该使用引用而不是转让所有权?

c++ - 在子类中调用基类的模板函数是否合法?

c++ - 我可以从基于范围的 for 中 move 元素吗?

c++ - 链表C++实现

javascript - OOO JavaScript : object self reference returns undefined but console shows it exists

Javascript:通过引用对象参数,理解赋值差异

flutter - 如何在 Flutter 中传递回调

c++ - 将 vector 的 vector 传递给函数

C++ 地址和指针