为什么是const&& as_const的重载删除了吗? [英] Why is the const&& overload of as_const deleted?

查看:99
本文介绍了为什么是const&& as_const的重载删除了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于C ++ 17进度的博客上,我读到以下内容:

On a blog on the progress of C++17 I read the following:


P0007 提出一个辅助函数模板 as_const ,它只是
引用并返回它作为对 const 的引用。

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 右值:

Consider what would happen if you didn't have that overload, and try to pass in a const rvalue:

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 后立即销毁。几乎所有采用左值的用户(无论是变量还是函数参数)都不希望传递临时值;默默地接受临时人员意味着您可以轻松地默默地获得悬挂的引用。

This would be accepted because T would be deduced as const S, and temporaries can bind to const S &. The result would be that you accidentally get an lvalue reference to a temporary, which will be destroyed right after ref has been initialised. Almost all users taking lvalues (whether variables or function parameters) don't expect to be passed temporaries; silently accepting temporaries means that you easily silently get dangling references.

这篇关于为什么是const&amp;&amp; as_const的重载删除了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆