c++ - 另一个 C++ 临时生命周期困惑

标签 c++

在下面的代码片段中...存储对 Quote::toXML 返回的临时字符串的引用是否安全?在ToXML::s_成员变量,至少只要与 << 一起使用即可仅运营商? IE。是子表达式 q.toXML 的结果活着直到下一个;

这里的完整表达是什么? q.toXML的返回值。整个std::cout或调用ToXML构造函数?

#include <iostream>
#include <string>

struct ToXML
{
    ToXML(char const * const tag, std::string const & s) : tag_(tag), s_(s)
    {
    }

    char const * tag_;
    std::string const & s_;
};

std::ostream & operator << (std::ostream & os, ToXML const & v)
{
    return os << "<" << v.tag_ << ">" << v.s_ << "</" << v.tag_ << ">";
}

struct Quote
{
    std::string toXML() const
    {
        return "<Quote/>";
    }
};

int main()
{
    Quote q;
    std::cout << ToXML("quote", q.toXML()) << std::endl;
    return 0;
}

最佳答案

是的,它很安全。

来自[class.temp]:

There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. [...]

The second context is when a reference is bound to a temporary.117 The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
— A temporary object bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.

我们正处于那个要点中。临时对象绑定(bind)到引用参数 (s) 并持续存在,直到包含调用的完整表达式完成为止。也就是说,它会一直持续到

std::cout << ToXML("quote", q.toXML()) << std::endl;
// --- here ---------------------------------------^

由于它在整个使用过程中持续存在,因此非常安全。但是,一旦您执行以下操作:

ToXML x("quote", q.toXML());

你被悬空引用困住了,所以我会谨慎使用这个模式。

关于c++ - 另一个 C++ 临时生命周期困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32813694/

相关文章:

android - 使用 Android NDK 从字符串路径打开文件

c++ - 缓存行对齐的内存分配会得到返回吗?

c++ - 打印一个序列中的 1 的数量,直到一个数字,而不实际计算 1

c++ - 在C++中使用Bitset将16位显示为四组4位

c++ - 来自 openCV 的 imread 使图像变暗

c++ - 有没有办法替换库中的函数?

c++ - Visual Studio 跳过构建

c++ - 在 C++ 中管理内存的理念是什么?

c++ - C++中指向函数的指针

C++ 摆脱空字符串行