C ++临时人员的生存期-这样安全吗? [英] C++ lifetime of temporaries - is this safe?

查看:48
本文介绍了C ++临时人员的生存期-这样安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我正确理解了临时生存期的规则,则此代码应该是安全的,因为 make_string()中的临时 stringstream 的生​​存期一直持续到完整的表达.我不是100%确信这里没有细微的问题,任何人都可以确认这种使用方式是否安全吗?在clang和 gcc 中,它似乎可以正常工作.

If I understand the rules for the lifetime of temporaries correctly, this code should be safe since the lifetime of the temporary stringstream in make_string() lasts until the end of the complete expression. I'm not 100% confident there's not a subtle problem here though, can anyone confirm if this usage pattern is safe? It appears to work fine in clang and gcc.

#include <iomanip>
#include <iostream>
#include <sstream>

using namespace std;

ostringstream& make_string_impl(ostringstream&& s) { return s; }

template<typename T, typename... Ts>
ostringstream& make_string_impl(ostringstream&& s, T&& t, Ts&&... ts) {
    s << t;
    return make_string_impl(std::move(s), std::forward<Ts>(ts)...);
}

template<typename... Ts>
string make_string(Ts&&... ts) {
    return make_string_impl(ostringstream{}, std::forward<Ts>(ts)...).str();
}

int main() {
    cout << make_string("Hello, ", 5, " World!", '\n', 10.0, "\n0x", hex, 15, "\n");
}

推荐答案

该标准的相关部分在§12.2中:

The relevant part of the standard is in §12.2:

12.2.3)临时对象被销毁为最后一步在评估全表达式(1.9)时(按词法)包含创建它们的点.

12.2.3) Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.

除了:

12.2.4)在两种情况下,临时变量在与完整表达式结束时不同的位置被销毁.第一个上下文是调用默认构造以初始化数组的元素时.... [不适用]

12.2.5)第二种情况是引用绑定到临时项时.引用绑定到的临时对象或引用绑定到的子对象的完整对象的临时对象在引用的生存期内一直存在,除了:

12.2.5) The second context is when a reference is bound to a temporary. 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:

  • ...

  • ...

与函数调用(5.2.2)中的参考参数绑定的临时对象一直存在,直到包含该调用的完整表达式完成为止.

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.

所以你去了.临时 stringstream {} 绑定到函数调用中的引用,因此它一直存在,直到表达式完成.这很安全.

So there you go. The temporary stringstream{} is bound to a reference in a function call, so it persists until the completion of the expression. This is safe.

这篇关于C ++临时人员的生存期-这样安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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