Why declare a deleted assignment operators with the ref-qualifier &

烂漫一生 提交于 2021-01-28 06:31:34

问题


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

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