c++assignment-operatorrule-of-five

Can assignment operations which declared as default have reference qualifiers?


When declaring assignment operations as default, is there anything wrong to make them reference qualified to prevent assignment to temporaries? (Most often than not, it prevents stupid errors). Common resources, do not say anything about reference qualifiers for "default" operations, and almost every example I've seen so far, doesn't declare them with proper ref-qualifier.

Does language standard say anything about reference qualifiers declaring assignment operations as default.

  1. It is allowed?
  2. Is there anything wrong about doing that? After all, with very few exceptions, assigning to rvalues doesn't make sense.
  3. I understand that they were not made reference qualified by default for backwards compatibility, however is there a reason not to that? (In case that the answer to first question is "yes" and the answer to the second one is "no").

Solution

  • It is allowed to define a defaulted assignment operator with an additional ref-qualifier. See [dcl.fct.def.default]/2.1.

    Whether or not you should actually do it is an opinion-based question. I don't see anything obviously wrong with adding a &, but I suspect that you'll encounter resistance if you try to convince everyone on your team to do it, because it may indeed catch some bugs, but very few, and almost all of those bugs are likely to be inside unit tests anyway. (In contrast, bugs like if (x = 3), where the left side is an lvalue, are much more common, and you won't catch those, but maybe the compiler will issue a warning.)

    It's sort of like how you might have trouble convincing people to declare their const char* variables as const char* const if they know the pointer isn't going to change. Sure, it increases safety by a bit, but it also requires extra typing.