Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate vector size with list initialization (curly braces)

How can I do the equivalent of:

#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer(bufferSize, ' ');

With list (curly braced) initialization?

When I try to do the following:

#include <vector>

size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer {bufferSize, ' '};

It wrongly interprets bufferSize as the value to be stored in the first index of the container (i.e. calls the wrong std::vector constructor), and fails to compile due to invalid narrowing conversion from unsigned int (size_t) to unsigned char.

like image 761
not an alien Avatar asked Nov 29 '18 15:11

not an alien


1 Answers

Short answer: you don't.

This is not a problem with uniform initialization per se, but with std::initializer_list. There is a special rule in overload resolution that always gives priority to constructors taking std::initializer_list if list-initialization is used, regardless of the existence of other constructors which might require less implicit conversions.


I would suggest using

std::vector<unsigned char> buffer(bufferSize, ' ');

or, if you really want to use list-initialization, create your wrapper around std::vector that provides constructor overloads that do the right thing.

like image 154
Vittorio Romeo Avatar answered Oct 20 '22 17:10

Vittorio Romeo