怎么解释呢?"new"数组未初始化...?
how to explain this? A "new"-ed array is not initialized...?
我遇到了一些奇怪的事情:一个数组"new"-ed在堆中随机值…
我用下面的代码做了一个测试:class Solution_046 {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> rst;
int sz = nums.size();
if(sz)
{
vector<int> group;
int* inuse = new int[sz];
cout<<"--------- inuse ------------"<<endl;
for(int ii=0; ii<sz; ++ii)
//inuse[ii]=0, cout<<inuse[ii]<<", ";
cout<<inuse[ii]<<",, ";
cout<<endl;
//......
}
return rst;
}
};
int main()
{
Solution_046 s046;
vector<int> vv;
vv.push_back(1);
vv.push_back(2);
vv.push_back(3);
vv.push_back(4);
vv.push_back(5);
vv.push_back(6);
vv.push_back(7);
vector< vector<int> > rst = s046.permute(vv);
return 0;
}
如果我禁用其中一行或两行"vv.push_back(…)",那么打印的结果将包含一些随机值,而不是全部为零:
$ ./nc (with all 7 lines)
--------- inuse ------------
0,, 0,, 0,, 0,, 0,, 0,, 0,,
$ ./nc (disalbed one line)
--------- inuse ------------
29339680,, 0,, 4,, 5,, 0,, 0,,
$ ./nc (disabled two lines)
--------- inuse ------------
26095648,, 0,, 5,, 6,, 0,,
$ ./nc (disabled three lines)
--------- inuse ------------
0,, 0,, 0,, 0,,
$ ./nc (disabled four lines)
--------- inuse ------------
0,, 0,, 0,, 0,,
$ ./nc (disabled five lines)
--------- inuse ------------
0,, 0,,
$ ./nc (disabled six lines)
--------- inuse ------------
0,,
在禁用一行或两行时会发生什么,为什么在"new"-ed数组中存在非零值?
int* inuse = new int[sz];
这个调用将为int
数组分配内存,但它不会对内容进行值初始化。如果您想用零初始化,请使用以下语法:
int* inuse = new int[sz]();
int* inuse = new int[sz]{}; //c++11
初始化为零是任意的,通常是不必要的,并且开销不是特别低。所以语言默认不会这样做。
使用未初始化的数组元素在c++中是未定义的行为。
可以通过在new
: new int[sz]{};
之后使用{}
来强制零初始化。正式地,将内存块设置为零。
相关文章:
- C++使用整数的压缩数组初始化对象
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 new 和 值进行数组初始化,但没有显式数量的元素
- 运行时C++数组初始化问题
- 使用带有参数包的数组的成员数组初始化类
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- C++ 2 个指针数组初始化 C2440
- C++结构字符数组初始化
- C++中的多维数组初始化
- constexpr数组初始化
- C++引物动态数组初始化程序的数目超过大小
- 使用std::index_sequence对std::数组初始化进行包扩展
- 当 std 数组初始化太小时,C++会引发错误吗?
- 如何确定结构数组初始化的大小?
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 此代码中的数组初始化样式是什么?这是标准的吗?
- C++ 使用数组初始化时的 STL 向量内存管理