Search code examples
c++c++11list-initialization

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.


Solution

  • 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.