JohnB
JohnB

Reputation: 13733

Conversion from size_t to wchar_t requires a narrowing conversion

Trying to compile the following snippet of code

static std::vector<wchar_t> produceStrings(int n) {
   std::size_t vsize = 4 * n;
   auto v = std::vector<wchar_t>{ vsize };
   // ...
}

in VS2015 gives me the error:

error C2398: Element '1': conversion from 'size_t' to 'wchar_t'
requires a narrowing conversion

Replacing the definition of v by

std::vector<wchar_t> v(vsize);

however, works. Replacing vsize by, e.g., 10, works as well.

Why?

Edit: I am compiling for 32 bit.

Upvotes: 2

Views: 952

Answers (1)

Michael Oliver
Michael Oliver

Reputation: 1412

std::vector<wchar_t>{ vsize }; tries to create a vector with only the element vsize in it, which does a conversion from size_t to wchar_t.

std::vector<wchar_t>(vsize); constructs a vector with vsize elements reserved, which is perfectly fine.

Upvotes: 5

Related Questions