Does it improve safety to mark assignment operators as lvalue-only?

蹲街弑〆低调 提交于 2019-11-28 12:03:25

In my experience in the rare case you do want to assign to an rvalue, writing

template<class T>
std::remove_reference_t<T>& as_lvalue(T&&t){return t;}

and doing as_lvalue( tmp() ) = foo instead of tmp()=foo is not a huge barrier. It does mean that the occasional bit of code that did assign to an rvalue is now going to break; I personally would suspect most such cases are actually uncaught bugs.


Restricting every type in std to be lvalue-restricted on operator= was considered during C++11 standardization in Frankfurt (2009/07). The resolution reasoning recorded in the minutes was:

N2819, "N2819 Ref-Qualifiers for assignment operators of the Standard Library" was initially considered by the LWG. This proposal sought to change 350 copy-assignment operators in the C++ standard library to prevent assignment operations in which the left operand is an rvalue. Due to the large number of changes required, the proposal was sent to EWG, with the request that the default behavior for implicit copy-assignment operators be reconsidered, so that assignment to an rvalue is not permitted. The EWG resolved to maintain the status quo, because of concerns about backwards compatibility.

I read that as saying "350 changes? How about a language change?". EWG said "no, that language change could break compatibility". And possibly the proposal died on the vine.

In 2009, C++11 (then C++0x) was already behind schedule. As the proposition involved 300 changes to the library that (in theory) could cause regressions. No other reason was cited in the minutes. It being declined for not being worth the pain of regressions (or even checking for the frequency of regressions!) is understandable. So I wouldn't presume prejudice on the idea just because C++ rejected it in std.

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