c++ - 如何禁止赋值

标签 c++ c++11

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:

  1. 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=,只能在编译器找到更可取的重载解决方案时使用。但是,这样的重载不可能存在,因为 Xconst X& 作为参数无法区分([over.ics.rank] §13.3.3.2)并且返回值被忽略.

话虽这么说使用规范签名是有风格原因的。这个问题存在的事实表明,阅读您的代码的任何人都可能知道其含义并假设它在做一些特殊的事情。为了便于阅读,我建议您使用熟悉的 X& operator=(const X&) = delete;

关于c++ - 如何禁止赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34186324/

相关文章:

c++ - 如何在没有延迟的情况下从 Win32 中的另一个进程捕获标准输出?

c++ - 围绕另一个对象旋转对象

c++ - pthread_mutex_lock.c :62: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed

c++ - 延迟构造的 shared_ptr

c++ - 是否有满足 C99 标准的 static_assert 替代品?

c++ - 为什么用户定义的复制构造函数调用基本构造函数,而默认复制构造函数则不调用?

c++ - 有谁知道我在哪里可以找到标准的 Windows 文件对话框工具栏图标?

c++ - 在C++中避免for循环。但为什么?

c++ - 谁能解释当前 C++0x 标准草案的这一段?

c++ - 使用 libstdc++ 在字符串、u16string 和 u32string 之间转换