Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no vector(size_type n, const Allocator& alloc) in C++11?

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?

like image 854
rkjnsn Avatar asked Feb 23 '12 22:02

rkjnsn


2 Answers

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.

like image 188
Nicol Bolas Avatar answered Nov 15 '22 05:11

Nicol Bolas


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.

like image 42
Xeo Avatar answered Nov 15 '22 05:11

Xeo