我在此代码的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
我发现了一个类似的问题:Why does C++ require a user-provided default constructor to default-construct a const object?,从答案看来A
应该是const-default-constructible的,而clang有一个错误。这里谁是正确的?
c声更聪明。您将如何使用统一化const属性?
无论如何,这是固定的:
#include <vector>
struct A { const std::vector<int> v {}; };
int main() { A a; }