为什么删除了as_const的const &&重载?

Ral*_*zky 20 c++ templates const c++17

关于C++ 17进展的博客上,我阅读了以下内容:

P0007提出一个辅助函数模板as_const,它只需要一个引用并将其作为引用返回const.

template <typename T> std::add_const_t<T>& as_const(T& t) { return t }
template <typename T> void as_const(T const&&) = delete;
Run Code Online (Sandbox Code Playgroud)

为什么const&&删除了重载?

小智 13

考虑如果你没有那个重载会发生什么,并尝试传入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
}
Run Code Online (Sandbox Code Playgroud)

这将被接受,因为T它将被推断为const S,并且临时工可以绑定const S &.结果是你不小心得到一个临时的左值引用,它将ref在初始化后立即销毁.几乎所有采用左值(无论是变量还是函数参数)的用户都不希望传递临时值; 默默地接受临时的意味着你很容易默默地获得悬挂的参考.