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

标签 c++ c++11

如果我正确理解了临时对象生命周期的规则,这段代码应该是安全的,因为 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/

相关文章:

c++ - 节点之间的存储成本

c++ - 删除链接列表中的每隔三个节点

c++ - C++ lambda 的返回类型

具有右值引用的 C++ 模板化方法消歧规则

c++ - 没有额外的实例方法和变量的对象切片

c++ - 如何使用 C++ 中的 Write 系统调用?

c++ - 如何为 Windows 实现终端仿真器?

c++ - 没有模板左值不匹配(&&),但有模板匹配(T &&)?

c++ - 在类中存储 Lambda

c++ - 为什么从方法返回时局部变量中的数据会损坏?