gpt4 book ai didi

c++ - 为什么在 const 成员结构中需要构造函数?

转载 作者:IT老高 更新时间:2023-10-28 12:34:40 25 4
gpt4 key购买 nike

我有一个类似这样的代码:

class AClass {
public:
struct AStruct { };

AClass(){}

private:
const AStruct m_struct;
};

int main() {
AClass a;
}

它抛出这个编译错误(Clang LLVM 5.1 版):

error: constructor for 'AClass' must explicitly initialize 
the const member 'm_struct'

如果我为 struct AStruct 指定 C++11 默认构造函数,我会得到同样的错误:

  struct AStruct {
AStruct() = default;
};

但是,这可以通过编写一个空主体的构造函数来解决:

  struct AStruct {
AStruct(){} // fixed
};

为什么我需要指定一个空的构造函数?它不是自动创建的,对结构有公共(public)访问权限吗?

为什么C++11默认构造函数没有解决问题?

最佳答案

来自 §8.5 [dcl.init]/7:

If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

AClass 的默认构造函数默认初始化 const 成员(见下文),因此该成员必须具有用户提供的默认构造函数。使用 = default 不会产生用户提供的默认构造函数,如 §8.4.2 [dcl.fct.def.default]/4:

A function is user-provided if it is user-declared and not explicitly defaulted ordeleted on its first declaration.


根据 §12.6.2 [class.base.init]/8 对成员进行默认初始化:

In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer) and the entity is not a virtual base class of an abstract class (10.4), then

— if the entity is a non-static data member that has a brace-or-equal-initializer , the entity is initialized as specified in 8.5;
— otherwise, if the entity is an anonymous union or a variant member (9.5), no initialization is performed;
otherwise, the entity is default-initialized (8.5).

关于c++ - 为什么在 const 成员结构中需要构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24943665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com