我找到了一段代码如下:
std::pair<const ColumnPtr&, bool> unpack_if_const(const ColumnPtr& ptr) noexcept {
if (is_column_const(*ptr)) {
return std::make_pair(static_cast<const ColumnConst&>(*ptr).get_data_column_ptr(), true);
}
return std::make_pair(ptr, false);
}
想接收返回值的
first
作为参考时出现问题
const auto& [lcol, left_const] =
unpack_if_const(block.get_by_position(arguments[0]).column);
但是现在你会看到
lcol
是一个 悬空引用.
发现LLVM的开发者亲切地说:
* Since C++11 they have been passed by forwarding reference and then
* forwarded to the new members of the pair. To create a pair with a
* member of reference type, pass a `reference_wrapper` to this function.
在
make_pair
的评论中。
所以我想知道如何实现它?如何
传递一个
给这个函数。reference_wrapper
如果
block.get_by_position(arguments[0])
通过引用返回,而 ColumnConst::get_data_column_ptr()
也通过引用返回,那么这里根本没有悬空引用(在您修复make_pair
之后)
为了防止
const ColumnPtr& ptr
绑定到一个临时的,你可以删除一个右值重载:
std::pair<const ColumnPtr&, bool> unpack_if_const(ColumnPtr&& ptr) = delete;
std::pair<const ColumnPtr&, bool> unpack_if_const(const ColumnPtr& ptr) noexcept {
if (is_column_const(*ptr)) {
return { static_cast<const ColumnConst&>(*ptr).get_data_column_ptr(), true };
}
// return std::pair<const ColumnPtr&, bool>(ptr, false);
return { ptr, false };
}
然后代替
auto [lcol, left_const] = unpack_if_const(<temporary initializer>);
,你必须写auto obj = <temporary initializer>; auto [lcol, left_const] = unpack_if_const(obj);
,它不会有悬空引用