Search code examples
c++memoryvectormemory-managementdynamic-memory-allocation

How much memory allocated with vector initialized with initializer lists and push_back


If I have these 2 lines of code in C++

vector<int> vec = {3,4,5};
vec.push_back(6);

How much memory is allocated in total for the 2 lines and what assumption we need to make? I tried to look these up but can't find the definition for these anywhere.


Solution

  • Looking at llvm's libcxx library as an example, we could speculate that the capacity would be 6 ints in size.

    vector<int> vec = {3,4,5}; allocates 3 ints on initialization __vallocate(3);

    template <class _Tp, class _Allocator>
    inline _LIBCPP_INLINE_VISIBILITY
    vector<_Tp, _Allocator>::vector(initializer_list<value_type> __il)
    {
    #if _LIBCPP_DEBUG_LEVEL >= 2
        __get_db()->__insert_c(this);
    #endif
        if (__il.size() > 0)
        {
            __vallocate(__il.size());
            __construct_at_end(__il.begin(), __il.end(), __il.size());
        }
    }
    

    vec.push_back(6); triggers re-allocation with a doubling in capacity 2*__cap

    //  Precondition:  __new_size > capacity()
    template <class _Tp, class _Allocator>
    inline _LIBCPP_INLINE_VISIBILITY
    typename vector<_Tp, _Allocator>::size_type
    vector<_Tp, _Allocator>::__recommend(size_type __new_size) const
    {
        const size_type __ms = max_size();
        if (__new_size > __ms)
            this->__throw_length_error();
        const size_type __cap = capacity();
        if (__cap >= __ms / 2)
            return __ms;
        return _VSTD::max<size_type>(2*__cap, __new_size);
    }
    

    https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/include/vector

    Update (based on ChrisD's comment)

    Since the capacity multiplier could be in the range of 1.5 to 2, the size could be 4, 5, or 6 ints.