c++ - 具有 const 成员的类构造

标签 c++ constructor constants

我有一个名为 Test 的类,它有一个名为 aconst int 成员:

class Test {
public:
    const int a;
};

然后我实例化一个名为test的Test对象:

Test test;

并得到一个合理的编译错误“错误:‘class Test’中未初始化的 const 成员”,但是当我这样做时发生了一些奇怪的事情:

Test test = Test();

没有编译错误,发生了什么? Test() 不会像 Test test; 那样调用默认构造函数然后调用默认复制构造函数吗?我使用的编译器是“gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4”,编译器配置为 c++11 模式。

最佳答案

第一次初始化

Test test;

一直是病式的。简而言之,不允许让 const 对象处于未初始化状态。

第二次初始化

Test test = Test();

在 C++98、C++03 和可能在 C++11 中的格式良好(但请参阅下面我的 P.S.)。然而它在 C++14 及更高版本中是病式的。

相关更改包含在 value-initialization 的定义中,为响应 () 初始化程序而执行。在 C++03(及之前)中,用户定义的默认构造函数的缺失导致值初始化完全忽略构造函数并作为独立于构造函数的初始化机制工作。 Test() 表达式将生成一个正确的零初始化临时对象。

但是,在 C++14 中,一个已删除的默认构造函数被值初始化以与用户定义的相同的方式处理:值初始化现在必须使用它,并且显然会失败,因为它已被删除

C++11 8.5 (n3242)

7 To value-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.

...

C++14 8.5 (n3690)

8 To value-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9) with either no default constructor (12.1) or a default constructor that is user-provided or deleted, then the object is default-initialized;

— if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;

...

(强调我的)。请注意在后一个版本中添加了“或删除”的措辞,它将具有删除的隐式默认构造函数的类从第二个要点转移到第一个要点。

因此,编译器在 C++14 模式下拒绝后者的初始化代码(并在 C++98/C++03 模式下接受它)。

换句话说,在你的情况下编译了第二个初始化,因为你的编译器显然是为 C++03 模式(或之前)配置的。

P.S. 我的 C++11 草案版本很可能(甚至非常有可能)已经过时。我没有 C++11 的最终版本。 C++11 的最终版本很可能包含与 C++14 相同的措辞。这也可以解释那些在 C++11 模式下拒绝它的编译器的行为。在那种情况下,分隔线在 C++03 和 C++11 之间传递。

关于c++ - 具有 const 成员的类构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39813276/

相关文章:

c++ - 在 C++ 中实现公钥加密的简单方法?

c++ - 如何在 unix 环境下使用 .in 和 .out 文件进行测试?

java - 为什么在创建对象时调用构造函数?

c++ - 防止重新定义构造函数定义的方法

c++ - 常量 reference_wrapper

C++ 常量静态 char* 数组

static - dart const 静态字段

c++ - 公共(public)接口(interface)方法的私有(private)实现

c++ - Windows 安全中心 API

java - 在类主体或构造函数中初始化类成员?