本文介绍了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.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 ++临时人员的生存期-这样安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:24