如果我正确理解临时对象的生命周期规则,则此代码应该是安全的,因为make_string()
中的临时对象stringstream
的生存期会持续到完整表达式的结尾。我不是100%自信的,虽然这里没有一个微妙的问题,任何人都可以确认这种使用模式是否安全?它似乎在叮当和gcc工作正常。C++临时对象的生命周期 - 是否安全?
#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");
}
在我看来,它应该没问题。 – 2014-11-07 03:12:01
从技术上讲,没关系,但我相信你会发现效率很低。考虑使用'operator <<'定义一个字符串生成器。 – 2014-11-07 03:23:02
@ Cheersandhth.-Alf取决于编译器内联程度如何。 – cdhowie 2014-11-07 03:23:45