简体   繁体   中英

Why does std::vector zero initilize its memory?

I recently noticed that std::vector does clear it's memory with zeros after allocating.

I have created similar containers before (although not std compliant) and I never needed to explicitly zero the memory before creating new items.

I can't see a reason to do that and I was just wondering why.

To illustrate :

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() seems to always return true while array_zeroed() returns false .

I am obviously missing something here but i don't know what.

When creating an std::vector with n elements (as opposed to just using reserve to reserve space for them without actually creating), the default constructor is invoked on each of the elements. In the case of number primitives (such as int s or double s) the action of the default constructor is to set the value to zero.

CPP reference documentation:

the below overloaded constructors zeroes out elements of non-class types such as int, which is different from the behavior of new[] , which leaves them uninitialized.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM