user3443063
user3443063

Reputation: 1615

Error C2440 when compiling a library with meson

I have code C++ that I want to compile as a library using meson where I get 2 kinds of errors

winnt.h uses typedef for wchar_t:

typedef wchar_t WCHAR;
typedef WCHAR *PWCHAR;

If I do this in my code I get Error C2440:

const PWCHAR Tokens[] = { L"A", L"B", L"C", L"D" };

If I change my code that error disappears:

 const wchar_t * Tokens[] = { L"A", L"B", L"C", L"D" };

I know in C, the type of a string literal is array of char, but in C++, it's array of const char which causes this error. I also know it is possible to change Zc:strictStrings in VStudio. But since I compile my code with meson how would I get rid of that error using meson?

Upvotes: 0

Views: 147

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

With the definition

const PWCHAR Tokens[] = { ... };

you declare that Tokens is an array of constant pointers. The data that those pointers are pointing to are not constant.

And as literal strings are constant you can't use them to initialize the array.

The working definition:

const wchar_t * Tokens[] = { ... };

Or the alternative

wchar_t const * Tokens[] = { ... };

Here you declare that Tokens is an array of (non-constant) pointers to constant wchar_t data. Which is correct for literal strings.

If you want to be portable and follow the C++ standard, using PWCHAR is simply not possible.


If you want the pointers themselves to be constant, you need to add another const qualifier for them:

wchar_t const * const Tokens[] = { ... };
//              ^^^^^
//              makes the pointers constant
//      ^^^^^
//      makes the data constant

Or as mentioned in a comment: Use std::wstring (and other standard C++ containers):

// Or std::array if the size if known and fixed at compile-time
std::vector<std::wstring> Tokens = { ... };

Upvotes: 1

Related Questions