gpt4 book ai didi

临时对象的 C++ 生命周期——这安全吗?

转载 作者:可可西里 更新时间:2023-11-01 15:22:27 24 4
gpt4 key购买 nike

如果我正确理解了临时对象生命周期的规则,这段代码应该是安全的,因为 make_string() 中的临时 stringstream 的生命周期一直持续到完整的表达。不过,我不是 100% 确信这里没有细微的问题,任何人都可以确认这种使用模式是否安全吗?它似乎在 clang 和 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 中:

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) There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. The first context is when a default construct is called to initialize an element of an array. ... [doesn't apply]

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:

  • ...

  • 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{} 绑定(bind)到函数调用中的引用,因此它一直存在到表达式完成为止。这是安全的。

关于临时对象的 C++ 生命周期——这安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26793315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com