[英]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
. 它错误地将
bufferSize
解释为要存储在容器的第一个索引中的值(即调用错误的std::vector
构造函数),并且由于unsigned int
( size_t
)到unsigned char
无效缩小转换而无法编译。
Short answer: you don't . 简短的回答: 你没有 。
This is not a problem with uniform initialization per se, but with std::initializer_list
. 这不是统一初始化本身的问题,而是使用
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. 在重载解析中有一个特殊的规则 ,如果使用了列表初始化 ,它总是优先考虑使用
std::initializer_list
构造函数 ,而不管是否存在可能需要较少隐式转换的其他构造函数。
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. 或者,如果你真的想使用列表初始化 ,在
std::vector
周围创建你的包装器,它提供了做正确事情的构造函数重载。
The two relevant overload of std::vector
are: std::vector
的两个相关重载是:
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
. 这两个重载具有明确的含义,其中第二个用于使用
std::initializer_list
的元素初始化向量。
Overload resolution prefer initializer-list constructors when list-initialization
is used. 使用
list-initialization
时,重载决策更喜欢初始化列表构造list-initialization
。
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). list-initialization
不允许缩小转换,您尝试使用T=unsigned char
创建std::vector
但是std::initializer_list
参数的推导T
是T= unsigned long
,这将涉及缩小转换(不是允许)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.