使用const int类型的std::array时触发编译错误的原因是什么?
std::array<const int, N>默认构造的编译错误 嘿,我来帮你理清这个编译错误的问题~
首先看你写的代码:
#include <array> #include <iostream> using namespace std; int main() { array<const int, 4> vals; return 0; }
对应的编译错误信息是:
test.cpp: In function ‘int main()’:
test.cpp:7:22: error: use of deleted function ‘std::array::array()’
array<const int,4> vals;
^~~~
In file included from test.cpp:1:0:
/usr/include/c++/7.3.0/array:94:12: note: ...(省略的内容为编译器补充说明std::array默认构造函数被删除的原因)
错误原因
本质问题在于:std::array的默认构造函数会尝试默认初始化它内部的所有元素,但const int类型是不可默认构造的。
C++规定const变量必须被显式赋予初始值——编译器没法自动给const int生成一个合法的默认值,所以当你声明array<const int,4> vals;时,std::array的默认构造函数无法完成元素初始化,因此这个构造函数被编译器标记为"删除(deleted)",也就导致了编译错误。
这和你直接写const int arr[4];会报错是同一个逻辑:你不能创建一个元素全是const的数组,却不给它们初始化值。
解决方案
根据你的需求,有几种可行的解决方式:
显式初始化所有元素
如果确实需要const int类型的数组,必须在声明时用初始化列表给每个元素赋值:array<const int, 4> vals = {10, 20, 30, 40}; // 或者用列表初始化的简化写法 array<const int, 4> vals{1, 2, 3, 4};移除元素的const限定
如果不需要元素是const类型,直接把const int改成int即可,这样std::array就能正常默认构造了(此时元素会被默认初始化,值为不确定但合法):array<int, 4> vals;借助其他构造方式初始化
如果你需要从已有数据源初始化const数组,也可以用std::array的拷贝构造或移动构造,比如:array<int, 4> temp = {1,2,3,4}; array<const int, 4> vals(temp);
内容的提问来源于stack exchange,提问作者Roger_88

