In C++11, std::vector has the constructor vector(size_type n)
which will default construct n
items in place, which can be used with default constructible, movable, non-copyable classes.
However, unlike every other vector constructor, there is no variant that takes an allocator, and I have resorted to the following:
// Foo is default constructible and moveable, but not copyable
const int n = 10; // Want 10 default constructed Foos
std::vector<Foo, CustomAllocator> foos(allocator);
foos.reserve(n);
for (int i = 0; i < n; ++i)
foos.emplace_back();
Is there a better way to accomplish this? Is there a specific reason vector(size_type n, const Allocator& alloc)
was omitted from the standard?
After thinking about it, it might not be a defect after all.
It is possible that allocator_type
and value_type
are perversely the same type. In that case, which function would vector(3, alloc)
call? The constructor that takes a default value to copy-initialize into all of the elements, or the one that takes a size and an allocator? That's ambiguous, and thus a compile error.
First, instead of your reserve
/loop thingy, you can simply use resize
to achieve what your imagined constructor would do:
const int n = 10;
std::vector<Foo, Alloc> foos(allocator);
foo.resize(n);
Another option is to use the three argument version of the size_type n
constructor:
const int n = 10;
std::vector<Foo, Alloc> foos(n, Foo(), allocator);
Though this actually copy constructs into the elements, which may or may not be acceptable.
On the rationale? No idea. Probably overlooked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With