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
.
std::initializer_list
constructors. It always prefer those constructors, hence it tries to invoke it and fails – JackelynjackeroobufferSize
issue would be even worse – Beauvoirauto var = type(stuff);
as it is easier for me to control which constructor I want to call. One of these days we might actually get this fixed though. – Catanzarovector{...}
to initialize from a list (including 0 elements), andvector(...)
to call all other constructors. "Universal" doesn't mean "this is the replacement". It just means you can now list initialize on all objects, rather than just some of them. – Commemorationstd::vector<int>
member should be constructed with a certain size, one can't just write something as compact asstd::vector<int> foo { some_size, 42 }
which actually creates the vector member withsome_size
elements which are initialized to 42. – Sheilahshekel