【发布时间】:2023-03-27 22:26:01
【问题描述】:
背景:
假设我有这样的事情:
struct item
{
int x;
item(int y): x(y) {}
}
class item_view
{
const item& it;
public:
item_view(const item& it_) : it(it_) {}
friend std::ostream& operator<<(std::ostream& os, const item_view& view)
{return os;} //actually is more complicated
}
我之所以不能只重载operator<<,是因为它更人性化,并且视图是用来将数据传递给SQL的,所以必须对记号和其他一些字符进行转义。
问题:
有人可能想做这样的事情:
auto view = item_view(2);
std::cout << view;
这似乎是未定义的行为。
问题:
如何防止临时构建item_view?
【问题讨论】:
-
显然?这里没有 UB... 由
2构造的临时对象一直存在到语句结束。 -
@Quentin,请注意。我相信人们使用它就像
auto view = item_view(2); std::cout << view;那当然应该是UB。 -
是的,那个时候是:)
-
顺便说一句,构造函数参数名称不需要与要初始化的数据成员名称不同。你可以使用
item(int x): x(x) {}和item_view(const item& it) : it(it) {}就好了。