问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/52444471/why-declare-a-deleted-assignment-operators-with-the-ref-qualifier