Saturday, 15 February 2014

c++11 - C++ lifetime of temporaries - is this safe? -



c++11 - C++ lifetime of temporaries - is this safe? -

if understand rules lifetime of temporaries correctly, code should safe since lifetime of temporary stringstream in make_string() lasts until end of finish expression. i'm not 100% confident there's not subtle problem here though, can confirm if usage pattern safe? appears work fine in clang , gcc.

#include <iomanip> #include <iostream> #include <sstream> using namespace std; ostringstream& make_string_impl(ostringstream&& s) { homecoming s; } template<typename t, typename... ts> ostringstream& make_string_impl(ostringstream&& s, t&& t, ts&&... ts) { s << t; homecoming make_string_impl(std::move(s), std::forward<ts>(ts)...); } template<typename... ts> string make_string(ts&&... ts) { homecoming make_string_impl(ostringstream{}, std::forward<ts>(ts)...).str(); } int main() { cout << make_string("hello, ", 5, " world!", '\n', 10.0, "\n0x", hex, 15, "\n"); }

the relevant part of standard in §12.2:

12.2.3) temporary objects destroyed lastly step in evaluating full-expression (1.9) (lexically) contains point created.

except:

12.2.4) there 2 contexts in temporaries destroyed @ different point end of full-expression. first context when default build called initialize element of array. ... [doesn't apply]

12.2.5) sec context when reference bound temporary. temporary reference bound or temporary finish object of subobject reference bound persists lifetime of reference except:

...

a temporary bound reference parameter in function phone call (5.2.2) persists until completion of full-expression containing call.

so there go. temporary stringstream{} bound reference in function call, persists until completion of expression. safe.

c++ c++11

No comments:

Post a Comment