首页 > 解决方案 > 调用具有 const 成员的类型的隐式删除的默认构造函数

问题描述

对于这段代码,我看到 gcc 和 clang 编译器之间的不同行为:

#include <vector>

struct A { const std::vector<int> v; };

int main() { A a; }

clang 无法编译它(https://godbolt.org/z/v-nEir):

<source>:5:16: error: call to implicitly-deleted default constructor of 'A'
int main() { A a; }
               ^
<source>:3:35: note: default constructor of 'A' is implicitly deleted because field 'v' of const-qualified type 'const std::vector<int>' would not be initialized

struct A { const std::vector<int> v; };

gcc 编译它没有错误:https ://godbolt.org/z/Sy96DU

我发现了一个类似的问题: 为什么 C++ 需要用户提供的默认构造函数来默认构造一个 const 对象?从答案看来A应该是 const-default-constructible 并且 clang 有一个错误。谁是正确的?

标签: c++clangdefault-constructor

解决方案


推荐阅读