Why is the const&& overload of as_const deleted?

烂漫一生 提交于 2019-12-09 14:07:44

问题


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

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;

Why is the const&& overload deleted?


回答1:


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
}

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.



来源:https://stackoverflow.com/questions/34566063/why-is-the-const-overload-of-as-const-deleted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!