Reputation: 2137
std::vector<int> v1(1000);
std::vector<std::vector<int>> v2(1000);
std::vector<std::vector<int>::const_iterator> v3(1000);
How elements of these 3 vectors initialized?
About int, I test it and I saw that all elements become 0. Is this standard? I believed that primitives remain undefined. I create a vector with 300000000 elements, give non-zero values, delete it and recreate it, to avoid OS memory clear for data safety. Elements of recreated vector were 0 too.
What about iterator? Is there a initial value (0) for default constructor or initial value remains undefined? When I check this, iterators point to 0, but this can be OS
When I create a special object to track constructors, I saw that for first object, vector run the default constructor and for all others it run the copy constructor. Is this standard?
Is there a way to completely avoid initialization of elements? Or I must create my own vector? (Oh my God, I always say NOT ANOTHER VECTOR IMPLEMENTATION) I ask because I use ultra huge sparse matrices with parallel processing, so I cannot use push_back() and of course I don't want useless initialization, when later I will change the value.
Upvotes: 8
Views: 17784
Reputation: 59811
In C++11 the specification for the constructor vector::vector(size_type n)
says that n
elements are default-inserted. This is being defined as an element initialized by the expression allocator_traits<Allocator>::construct(m, p)
(where m
is of the allocator type and p
a pointer to the type stored in the container). For the default allocator this expression is ::new (static_cast<void*>(p)) T()
(see 20.6.8.2
). This value-initializes each element.
Upvotes: 5
Reputation: 28762
You are using this constructor (for std::vector<>
):
explicit vector (size_type n, const T& value= T(), const Allocator& = Allocator());
Which has the following documentation:
Repetitive sequence constructor: Initializes the vector with its content set to a repetition,
n
times, of copies ofvalue
.
Since you do not specify the value
it takes the default-value of the parameter, T()
, which is int
in your case, so all elements will be 0
Upvotes: 13
Reputation: 124632
They are default initialized.
About int, I test it and I saw that all elements become 0. Is this standard? I believed that primitives remain undefined.
No, an uninitialized int
has an indeterminate value. These are default initialized, i.e.,
int i; // uninitialized, indeterminate value
int k = int(); // default initialized, value == 0
Upvotes: 5
Reputation: 308121
The elements of a vector are default initialized, which in the case of POD types means zero initialized. There's no way to avoid it with a standard vector.
Upvotes: 3