简体   繁体   中英

Allocate vector size with list initialization (curly braces)

How can I do the equivelant 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 (ie calls the wrong std::vector constructor), and fails to compile due to invalid narrowing conversion from unsigned int ( size_t ) to unsigned char .

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.

The two relevant overload of std::vector are:

explicit vector( size_type count, 
                 const T& value = T(),
                 const Allocator& alloc = Allocator()); //(1)
vector( std::initializer_list<T> init, 
        const Allocator& alloc = Allocator() ); // (2)

These two overload has clear meaning, where the second is used to initialize the vector with the elements of the std::initializer_list .

Overload resolution prefer initializer-list constructors when list-initialization is used.

Narrowing conversions are not allowed with list-initialization , you're trying to create a std::vector with T=unsigned char but the deduced T for the std::initializer_list parameter is T= unsigned long which will involve a narrowing conversion (not allowed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM