put_money 是按值还是按引用来保存其参数? [英] Does put_money hold its argument by value or reference?
本文介绍了put_money 是按值还是按引用来保存其参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是否会调用未定义的行为?
Does the following invoke undefined behavior?
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <experimental/iterator>
int main() {
long double values[] = {1, 2, 3};
std::transform(
std::begin(values), std::end(values),
std::experimental::make_ostream_joiner(std::cout, ", "),
[](long double v) {
return std::put_money(v + 1);
}
);
return 0;
}
我担心的是 return std::put_money(v + 1)
返回对临时 v + 1
的引用.
My worry is that return std::put_money(v + 1)
returns a reference to the temporary v + 1
.
推荐答案
标准 ([ext.manip]/6) 只定义了这个特定的表达式:
The standard ([ext.manip]/6) only defines this specific expression:
out << put_money(mon, intl);
同时mon
是如何存储的还没有具体说明,它绝对有可能成为一个悬空引用并成为UB.
It is unspecified how mon
is stored in the mean time, and it is definitely possible for it to become a dangling reference and be UB.
一个简单"的解决方法是让你自己的类知道你存储了值:
An "easy" fix is making your own class to know you store the value:
struct money_putter {
long double value;
template<class charT, class traits>
friend std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const money_putter& mon) {
return os << std::put_money(mon.value);
}
};
int main() {
int values[] = {1, 2, 3};
std::transform(
std::begin(values), std::end(values),
std::experimental::make_ostream_joiner(std::cout, ", "),
[](int i) {
return money_putter{i}; // or i + 1
}
);
return 0;
}
这篇关于put_money 是按值还是按引用来保存其参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文