我最近注意到std::vector确实在分配后用零清除了它的内存。

我之前已经创建了类似的容器(尽管不符合std),而且在创建新项目之前,我不需要显式地将内存归零。

我看不出这样做的理由,我只是想知道为什么。

为了显示 :

struct S {
    int s[128];
};

bool vector_zeroed() {
    std::vector<S> c;
    while(c.size() < 1000) {
        c.emplace_back();
    }

    bool zeroed = true;
    for(const auto& s : c) {
        for(int i : s.s) {
            zeroed &= i == 0;
         }
    }
    return zeroed;
}

bool array_zeroed() {
    bool zeroed = true;
    auto *s = new S[1000];
    for(int k = 0; k != 1000; ++k) {
        for(int i : s[k].s) {
            zeroed &= i == 0;
        }
    }
    delete[] s;
    return zeroed;
}


vector_zeroed()似乎总是返回true,而array_zeroed()返回false

我显然在这里错过了一些东西,但我不知道。

最佳答案

CPP参考文档:

下面的重载构造函数将非类类型的元素(例如int)清零,这与new []的行为不同,后者的行为未初始化。

explicit vector( size_type count );   (since C++11)  (until C++14)
explicit vector( size_type count, const Allocator& alloc = Allocator() );
(since C++14)


http://en.cppreference.com/w/cpp/container/vector/vector

关于c++ - 为什么std::vector零初始化其内存?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40382114/

10-11 22:54
查看更多