且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

错误:使用已删除的函数

更新时间:2022-02-26 08:44:19

错误消息明确指出默认构造函数已隐式被删除.它甚至说明了原因:该类包含一个非静态的 const 变量,该变量不会被默认构造函数初始化.

The error message clearly says that the default constructor has been deleted implicitly. It even says why: the class contains a non-static, const variable, which would not be initialized by the default ctor.

class X {
    const int x;
};

由于 X::xconst,它必须被初始化——但是默认的构造函数通常不会初始化它(因为它是一个 POD 类型).因此,要获得默认的ctor,您需要自己定义一个(并且必须初始化x).对于作为参考的成员,您可能会遇到同样的情况:

Since X::x is const, it must be initialized -- but a default ctor wouldn't normally initialize it (because it's a POD type). Therefore, to get a default ctor, you need to define one yourself (and it must initialize x). You can get the same kind of situation with a member that's a reference:

class X { 
    whatever &x;
};

可能值得注意的是,出于基本相同的原因,这两个也将禁用赋值运算符的隐式创建.隐式赋值运算符通常会按成员进行赋值,但是对于 const 成员或引用成员,它不能这样做,因为该成员不能被赋值.要使赋值起作用,您需要编写自己的赋值运算符.

It's probably worth noting that both of these will also disable implicit creation of an assignment operator as well, for essentially the same reason. The implicit assignment operator normally does members-wise assignment, but with a const member or reference member, it can't do that because the member can't be assigned. To make assignment work, you need to write your own assignment operator.

这就是为什么 const 成员应该通常是静态的——当您进行赋值时,无论如何都不能分配 const 成员.在典型情况下,您的所有实例都将具有相同的值,因此它们***共享对单个变量的访问权限,而不是拥有多个都具有相同值的变量副本.

This is why a const member should typically be static -- when you do an assignment, you can't assign the const member anyway. In a typical case all your instances are going to have the same value so they might as well share access to a single variable instead of having lots of copies of a variable that will all have the same value.

当然,创建具有不同值的实例是可能的——您(例如)在创建对象时传递一个值,因此两个不同的对象可以有两个不同的值.但是,如果您尝试执行诸如交换它们之类的操作,则 const 成员将保留其原始值而不是被交换.

It is possible, of course, to create instances with different values though -- you (for example) pass a value when you create the object, so two different objects can have two different values. If, however, you try to do something like swapping them, the const member will retain its original value instead of being swapped.