Search code examples
c++c++11vectorcalloczero-initialization

When I 0-Initialize a vector Does It Have the Same Effect as calloc?


So calloc calls on the OS to retrieve zeroed pages on the heap: https://stackoverflow.com/a/2688522/2642059

What about C++11's vector constructor that only takes a size_t and 0-initializes the values? Ask the OS for a zeroed page in the general case, or does it need to initialize it's self because the vector's elements may be a class with a default initializer, which defaults members to a non-zero value?


Solution

  • std::vector<T> is part of the implementation, which means we can only see the results, not necessarily the magic behind the scenes. Furthermore, the implementation itself may (partially) specialize std::vector<T> as long as the observable results stay the same.

    However, that doesn't mean std::vector<int> can just ask the OS for zeroed memory. It still has to go through std::allocator and ::operator new, even if you replaced the latter.

    Of course, by the laws of compiler magic, if the compiler knows that you didn't, it may still ask the OS directly. But the chief problem with that logic is separate compilation. When compiling A.cpp containing std::vector<int>, the compiler won't know that B.cpp contains ::operator new.