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

In C ++ 11, std :: vector has a vector(size_type n) constructor that will by default build n elements in place, which can be used with standard constructive, movable, non-copyable classes.

However, unlike any other vector constructor, there is no option that the allocator accepts, and I 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 do this? Is there a specific reason for vector(size_type n, const Allocator& alloc) in the standard?

+6
source share
2 answers

Thinking about it, this may not be a flaw.

It is possible that allocator_type and value_type are perverse of the same type. In this case, which function will call vector(3, alloc) ? A constructor that accepts a default value for copy-initialization to all elements, or one that accepts a size and allocator? This is ambiguous and therefore a compilation error.

+7
source

First, instead of your reserve / loop thingy, you can simply use resize to achieve what your imaginary constructor will do:

 const int n = 10; std::vector<Foo, Alloc> foos(allocator); foo.resize(n); 

Another option is to use three versions of the size_type n constructor argument:

 const int n = 10; std::vector<Foo, Alloc> foos(n, Foo(), allocator); 

Although this actually copies the designs into elements that may or may not be acceptable.

About the logic? No idea. Probably did not pay attention.

+6
source

Source: https://habr.com/ru/post/909224/


All Articles