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

问题描述

在,我读到以下内容:

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

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的重载删除了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:12