在 C++20 标准中,[dcl.fct.def.default] , 显式默认函数:
2 The type
T<sub>1</sub>
of an explicitly defaulted special member functionF
is allowed to differ from the typeT<sub>2</sub>
it would have had if it were implicitly declared, as follows:(2.1) —
T<sub>1</sub>
andT<sub>2</sub>
may have differing ref-qualifiers;(2.2) —
T<sub>1</sub>
andT<sub>2</sub>
may have differing exception specifications; and(2.3) — if
T<sub>2</sub>
has a parameter of typeconst C&
, the corresponding parameter ofT<sub>1</sub>
may be of typeC&
.If
T<sub>1</sub>
differs fromT<sub>2</sub>
in any other way, then:(2.4) — if
F
is an assignment operator, and the return type ofT<sub>1</sub>
differs from the return type ofT<sub>2</sub>
orT<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]/7 为 Wrapper(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/