2

As far as I know a user declared assignment operators differ from built-in operators, as explained by this stackoverflow answer. But why should one add the "&" to a deleted operator?

// C++
class MyType
{
public:
 // ...

  MyType& operator=(MyType const&) & = delete;
  MyType& operator=(MyType &&) & noexcept = default;

// more
};

I ask because my static code checker reports a rule violation here and I see no reason to add the "&" for a deleted operator. Do I miss something?

Barry
  • 286,269
  • 29
  • 621
  • 977
Sonic78
  • 680
  • 5
  • 19
  • Which static checker and what is the supposed violation? – luk32 Sep 21 '18 at 13:23
  • @luk32 We get it with Polyspace when following Autosar C++14 rules – mattsson Sep 06 '21 at 12:01
  • @luk32 I guess you will get the finding reported (for the default'ed operator) by all static analysis tools that supports A12-8-7 (AUTOSAR C++14, e.g. 17-10) or [HIC++ v4.0 12.5.7](https://www.perforce.com/resources/qac/high-integrity-cpp-coding-standard/special-member-functions). The rationale of the rule is that user declared assignment operators differ from built-in operators: they accept rvalues as parameters. Adding "&" prohibits rvalue parameters and ensures that calls can only be made on lvalue objects and not on temporaries. That is to avoid e.g. `func() = other_obj`. – Sonic78 Sep 09 '21 at 14:16
  • That's pretty interesting as well as Barry's answer. – luk32 Sep 10 '21 at 08:15

1 Answers1

4

There's no reason to add a & qualifier in this case.

The point is to prevent your class from being copy-assignable, period. The purpose of the & qualifier is to prevent an rvalue of your class from being copy-assignable (the & would prevent the copy assignment operator from being a viable function in this case). But that's not your goal here - you want all copy assignment to be ill-formed, so that's just:

MyType& operator=(MyType const&) = delete;

And complain to whomever wrote that static check.


The issue with:

MyType& operator=(MyType const&) & = delete;

is that extra precision on the operator you're deleting suggests an intent that isn't there. I immediately am led to wonder if somewhere later in the class, for some reason, you have:

MyType& operator=(MyType const&) && { ... }

And you don't, because that's silly.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • If `MyType& operator=(MyType const&) & = delete;` is defined, whereas there is no definition about `MyType& operator=(MyType const&) &&`, does `MyType()=MyType()` compiles? And why? – John Apr 06 '22 at 07:17