Is the above program a guarantee of returning 0 in C ++ 14? Why?
Yes. From [vector.capacity]:
void resize(size_type sz);
13 Effects: If sz < size() , erases the last size() - sz elements from the sequence. Otherwise, add sz - size() to the default elements added to the sequence.
Where, from [container.requirements.general]:
An element X set by default if it is initialized by evaluating the expression allocator_traits<A>::construct(m, p) , where p is the uninitialized storage address for the element allocated in X
construct for std::allocator<T> does, from [default.allocator]:
template <class U, class... Args> void construct(U* p, Args&&... args);
Effects: ::new((void *)p) U(std::forward<Args>(args)...)
So this is initialization of values. We are doing new S() , not new S , so member X will be initialized to zero.
Ways to avoid this behavior (if desired):
- Change the distributor. Provide your own type of dispenser that has two overloads for
construct : one empty (which will do the initialization by default) and one accepts Args&&... - Change the type. Add a default constructor to
S that does not initialize.
Barry
source share