hackingcpp / comments

Comments regarding hackingcpp.com
0 stars 0 forks source link

cpp/recipe/uninitialized_numeric_array #2

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Allocate Uninitialized Numeric Array/Vector C++ | hacking C++

How to allocate (large) uninitialized numeric arrays / vectors without costly zero-initialization. The approaches presented vary in their degrees of convenience, safety and ISO standard support.

https://hackingcpp.com/cpp/recipe/uninitialized_numeric_array.html

maximiliank commented 3 years ago

Hi,

I think it is worth mentioning that this can be achieved with a custom allocator. A very good example can be found at stackoverflow. You can then simply use it:

using Vec = std::vector<int, default_init_allocator<int>>;
Vec v(1'000'000'000);

This works with std::span, std::vector and C style parameters. For std::vector you would have to include the allocator as well in the template parameters, e.g.

template<typename T, typename Allocator = std::allocator<T>>
void f(const std::vector<T, Allocator>& v)
{
}

Best regards Max

hackingcpp commented 3 years ago

@maximiliank: thanks for reminding me of modifying allocator::construct, yes that's also a good solution and I had completely forgotten about it. I'll add it. If one already uses a polymorphic allocator in a project, it's even easier to just switch the allocator.

hackingcpp commented 3 years ago

just sad, that the new standard memory resources only do allocation/deallocation, so one can't use std::pmr::polymorphic_allocator and had to write a custom polymorphic allocator