为什么 as_const 的 const&& 重载被删除了?
Why is the const&& overload of as_const deleted?
我在 blog on the progress of C++17 上阅读了以下内容:
P0007
proposes a helper function template as_const
, which simply
takes a reference and returns it as a reference to const
.
template <typename T> std::add_const_t<T>& as_const(T& t) { return t }
template <typename T> void as_const(T const&&) = delete;
为什么删除了 const&&
重载?
考虑如果没有那个重载会发生什么,并尝试传入一个 const
右值:
template <typename T> const T &as_const(T &t) { return t; }
struct S { };
const S f() { return S{}; }
int main() {
// auto & ref = as_const(S()); // correctly detected as invalid already
auto & ref = as_const(f()); // accepted
}
这将被接受,因为 T
将被推断为 const S
,并且临时对象可以绑定到 const S &
。结果是你不小心得到了一个临时的左值引用,它会在 ref
初始化后立即被销毁。几乎所有接受左值(无论是变量还是函数参数)的用户都不希望被临时传递;默默地接受临时对象意味着你很容易默默地获得悬空引用。
我在 blog on the progress of C++17 上阅读了以下内容:
P0007
proposes a helper function templateas_const
, which simply takes a reference and returns it as a reference toconst
.template <typename T> std::add_const_t<T>& as_const(T& t) { return t } template <typename T> void as_const(T const&&) = delete;
为什么删除了 const&&
重载?
考虑如果没有那个重载会发生什么,并尝试传入一个 const
右值:
template <typename T> const T &as_const(T &t) { return t; }
struct S { };
const S f() { return S{}; }
int main() {
// auto & ref = as_const(S()); // correctly detected as invalid already
auto & ref = as_const(f()); // accepted
}
这将被接受,因为 T
将被推断为 const S
,并且临时对象可以绑定到 const S &
。结果是你不小心得到了一个临时的左值引用,它会在 ref
初始化后立即被销毁。几乎所有接受左值(无论是变量还是函数参数)的用户都不希望被临时传递;默默地接受临时对象意味着你很容易默默地获得悬空引用。