c++ - 格式良好的类定义示例,其中包含编译器删除的默认特殊成员函数

标签 c++ class default c++20 function-definition

在 C++20 标准中,[dcl.fct.def.default] , 显式默认函数:

2 The type T<sub>1</sub> of an explicitly defaulted special member function F is allowed to differ from the type T<sub>2</sub> it would have had if it were implicitly declared, as follows:

(2.1) — T<sub>1</sub> and T<sub>2</sub> may have differing ref-qualifiers;

(2.2) — T<sub>1</sub> and T<sub>2</sub> may have differing exception specifications; and

(2.3) — if T<sub>2</sub> has a parameter of type const C&, the corresponding parameter of T<sub>1</sub> may be of type C&.

If T<sub>1</sub> differs from T<sub>2</sub> in any other way, then:

(2.4) — if F is an assignment operator, and the return type of T<sub>1</sub> differs from the return type of T<sub>2</sub> or T<sub>1</sub>’s parameter type is not a reference, the program is ill-formed;

(2.5) — otherwise, if F is explicitly defaulted on its first declaration, it is defined as deleted;

(2.6) — otherwise, the program is ill-formed

任何人都可以提供一个显式默认并被编译器删除的特殊成员函数的示例吗?函数声明应该格式良好。

最佳答案

来自 P0641 的示例,由此而来的措辞:

struct MyType {
  MyType(MyType&);  // no 'const'
};

template <typename T>
struct Wrapper {
  Wrapper(const Wrapper&) = default;
  T t;
};

Wrapper<MyType> var;  // fails to instantiate

假设实际上有一个默认构造函数。

这在以前是不正确的。现在,T<sub>1</sub> ( Wrapper 的复制构造函数)与隐式声明的情况不同(每个 [class.copy.ctor]/7Wrapper(Wrapper&) )。这与第一组项目符号中的情况不匹配(这里 T<sub>1</sub>const& 但没有 T<sub>2</sub> ,项目符号的顺序相反),所以我们进入第二组项目符号 - 并且我们最终得到 Wrapper<MyType>的复制构造函数被删除。


在代码中出现这种情况的一个很好的例子是 std::tuple (参见 LWG2086 ),在这些更改之前:

struct A {
  A();
  A(A&);
};
std::tuple<A> x; // ill-formed

现在,这是格式良好的,就是 tuple<A>是不可复制的。

关于c++ - 格式良好的类定义示例,其中包含编译器删除的默认特殊成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60837479/

相关文章:

javascript - ES6 将对象传递给构造函数并设置属性

c# - 以下哪个声明在程序的类级别是无效的

ios - 在 iOS 设备中获取默认用户电子邮件

java - 重载真的是 Java 中获取方法参数默认值的唯一方法吗?

python - 利用函数参数的一次性绑定(bind)是个坏主意吗?

c++ - 无法将参数 1 从 'overloaded-function' 转换为 '...'

c++ - 停止直接执行主应用程序并从第二个应用程序执行?

c# - 我如何计算(手动)字符串的 SizeOf,以及一个类是否添加到一个大小?

c++ - 生成(不是这样)具有特定字符串出现的随机字符串

c++ - 是否可以在同一行上一个接一个地使用 cin 和 getline?