I would like to customize std::vector
behavior to not default-construct the element type (e.g. int
), as it is expensive to do this for a large vector.
Looking at this, the only way I can see to do this is to specialize std::allocator_traits<MyAllocator>::construct
. However, this doesn't seem to be possible, because the specialization must be in the same namespace as the original declaration.
Putting a specialization in namespace std
already doesn't seem right. And it's actually worse than that, because the STL implementation I am using actually puts std::allocator_traits
in namespace std::__u
(and that surely varies across STL implementations), so it seems very wrong to do this.
This is confusing because it seems like std::allocator_traits is designed to allow specialization, but I can't figure out how to actually do it. Is this simply a bad idea? If so, is there some other way to solve the problem (avoiding default construction of elements in STL containers)?
int
is to do nothing, but mostvector
overloads actually do "zero" initialization. #29766461 – Adornint
with no value? – Adornvector
. It might be possible to find a compiler that was not properly initialising data in the 90`s before they implement C++ 98 or 03 standard... – Macedonian0
value, and default construct classes. Wheras "Default" initialization will default construct classes, but will not initialize primitives with any specific value, so reading from them would be undefined behavior. See the link I'd attached. – Adornvector
constructor. – Macedonianvector
methods ensure that the values are "zero" initialized, so all theint
members will have the value zero. However, the "default" initializer for anint
(NOT the zero initializer) will leave the value undefined. However, there's no standard conforming way to have a vector "default" initialize it's members, as far as I can determine. One could "default" initialize anint
outside of the vector and then "value" initialize the members of the vector to be equal to the integer, but that's technically undefined behavior. – Adornint
with no value? A common use case is creating a vector of numbers that will be assigned from multiple threads. Then, it makes no sense to zero-initialize them first and it can take some overhead for very large vectors. Moreover, zero-initialization from a single thread only may result having all elements in a local memory of a single NUMA node, which may be undesirable. – Indulgence