怎么解释呢?"new"数组未初始化...?

how to explain this? A "new"-ed array is not initialized...?

本文关键字:数组 初始化 new 解释      更新时间:2023-10-16

我遇到了一些奇怪的事情:一个数组"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]{};之后使用{}强制零初始化。正式地,将内存块设置为零。