operator=
是否有理由使用“规范”签名
class X {
X& operator=(const X&) = delete;
X& operator=(X&&) = delete;
};
不仅仅是
class X {
void operator=(X) = delete;
};
当您只想删除
它时?
更新:
此外,请考虑 X
具有显式声明的移动或复制构造函数的情况。
class X {
public:
X(X&&);
};
在这种情况下,op=(X&&)
和 op=(const X&)
被隐式删除,但我想明确表示不允许赋值。
最佳答案
不,没有技术理由使用规范的复制赋值运算符签名。
如标准中所见,[dcl.fct.def.delete] §8.4.3:
- A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed. [ Note: This includes calling the function implicitly or explicitly and forming a pointer or pointer-to-member to the function. It applies even for references in expressions that are not potentially-evaluated. If a function is overloaded, it is referenced only if the function is selected by overload resolution. — end note ]
因此,删除函数的名称,在本例中为 operator=
,只能在编译器找到更可取的重载解决方案时使用。但是,这样的重载不可能存在,因为 X
和 const X&
作为参数无法区分([over.ics.rank] §13.3.3.2)并且返回值被忽略.
话虽这么说,使用规范签名是有风格原因的。这个问题存在的事实表明,阅读您的代码的任何人都可能不知道其含义并假设它在做一些特殊的事情。为了便于阅读,我建议您使用熟悉的 X& operator=(const X&) = delete;
。
关于c++ - 如何禁止赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34186324/