为什么as_const禁止右值参数? [英] Why does as_const forbid rvalue arguments?

查看:77
本文介绍了为什么as_const禁止右值参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问为什么 as_const 禁止右值参数,根据 cppreference.com(即标准人员为什么这样做,而不是为什么cppreference.com专门对此进行了引用.而且也不是在规范中将委员会的意图编成法典,只是为了确保:))).这个(人工的)示例将产生一个错误(用户希望使其保持常量以保持COW安静)

I wanted to ask why as_const forbids rvalue arguments, according to cppreference.com (i.e. why the Standards folks made it so, not why cppreference.com specifically quoted them on that. And also not where in the spec the intent of the committee is codified, just for making sure :))). This (artificial) example would yield an error (user wants to make it const to keep COW quiet)

QChar c = as_const(getQString())[0];

另一个问题的答案指出,如果我们 just 删除右值引用重载的删除,它将以无提示的方式将右值转换为左值.是的,但是为什么不优雅地处理右值并为右值输入返回const右值,为左值输入返回const左值?

Another question's answer notes that if we just remove the deletion of the rvalue reference overload, it would silently transform rvalues to lvalues. Right, but why not handle rvalues gracefully and return const rvalues for rvalue input and const lvalues for lvalue input?

推荐答案

一个原因可能是由于缺少所有权转移而对右值可能很危险

One reason might be that it could be dangerous on rvalues due to lack of ownership transfer

for (auto const &&value : as_const(getQString()))  // whoops!
{
}

并且可能没有令人信服的用例来证明无视这种可能性的合理性.

and that there might not be a compelling use case to justify disregarding this possibility.

这篇关于为什么as_const禁止右值参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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