C ++ vector changed for no reason

I have this piece of code:

#include<iostream>
#include<vector>

class A 
{
    private:
        static int x;

    public:
        A(){}
        ~A()
        {
            ++x;
            std::cout << "destroying A " << x << std::endl;
        }

};

int A::x(0);

int main (int args, char** argv) 
{
    std::vector<A> vectA(5); 
}

and when I ran it, I expected it to print 5 lines (i.e. the destructor is called for each of the 5 elements in the vector), but actually the output is:

destroying A 1
destroying A 2
destroying A 3
destroying A 4
destroying A 5
destroying A 6

mmm weird ...

so I change the main function to:

int main (int args, char** argv) 
{
    std::vector<A> vectA(5);
    std::cout << vectA.capacity() << std::endl; 
}

and now output:

destroying A 1
5
destroying A 2
destroying A 3
destroying A 4
destroying A 5
destroying A 6

, , vectA, A, ( , ) 5 ( , ). : vectA ? , (5) . - , ?

+4
1

++ 11 , count value:

explicit vector(size_type count, const T& value = T(), const Allocator& alloc = Allocator());

, ++ 11 , , count - :

explicit vector(size_type count);

++ 11 value, . ++ 11 .

+8

Source: https://habr.com/ru/post/1528124/


All Articles