c++ - 将 const 引用传递给 C++ 中的临时字符串对象是否安全?

标签 c++

考虑函数 f

void f(const std::string& s) {
    ...
}

像下面这样用固定字符串调用 f 是否安全:

f("abc");

最佳答案

"abc" 隐式构造的 std::string 的生命周期是直到对 f() 的调用结束。只要您不在 f() 结束后将引用保存在其他地方,它就绝对安全。

std::string const *pstr;

void f(std::string const &s)
{
    s.length(); // safe. s has an instance backing
                // it for the lifetime of this function.

    pstr = &s; // still technically safe, but only if you don't
               // dereference pstr after this function completes.
}

f("abc");

pstr->length(); // undefined behavior, the instance
                // pstr pointed to no longer exists.

关于c++ - 将 const 引用传递给 C++ 中的临时字符串对象是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13829714/

相关文章:

c++ - 你怎么知道当前对象是什么?

c++ - 如何确保在完成写入之前不读取文件

c++单例,奇怪的错误

c++ - 将 "ascii art"printf 放入 char 数组?

c++ - soci c++可以执行多条SQL语句吗?

c++ - Qt Creator:如何运行Windows批处理文件并获得结果

c++ - 为什么 Friend 函数不能访问类的私有(private)成员

c++ - __glibcxx_function_requires 和 __glibcxx_requires_valid_range 宏是如何工作的?

C++ std::string 在任何平台上都是 100% RAII?

c++ - Qt Connect 无法连接到插槽