我想问为什么as_const
禁止右值参数,根据 http://en.cppreference.com/w/cpp/utility/as_constcppreference.com(即为什么标准人员这样做,而不是为什么 cppreference.com 专门引用了他们。而且也没有在规范中编纂委员会的意图,只是为了确保:)))。这个(人为的)示例会产生错误(用户希望将其设置为 const 以保持 COW 安静)
QChar c = as_const(getQString())[0];
另一个问题的回答 https://stackoverflow.com/a/34566125/1848654注意到如果我们just删除右值引用重载的删除,它会默默地将右值转换为左值。是的,但为什么不优雅地处理右值并为右值输入返回 const 右值,为左值输入返回 const 左值?
问题是如何延长生命周期
const auto& s = as_const(getQString()); // Create dangling pointer
QChar c = s[0]; // UB :-/
一种可能性是以下重载(而不是删除的重载)
template< typename T >
const T as_const(T&& t) noexcept(noexcept(T(std::forward<T>(t))))
{
return std::forward<T>(t);
}
这涉及额外的建设,也许还有其他陷阱。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)