0

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

  • error C2440: 'initializing': cannot convert from 'const wchar_t [19]' to 'const PWCHAR' -note: Conversion from string literal loses const qualifier (see /Zc:strictStrings)
  • error C2664: '... cannot convert argument 2 from 'const wchar_t [6]' to 'PWSTR note: Conversion from string literal loses const qualifier (see /Zc:strictStrings)

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?

user3443063
  • 1,455
  • 4
  • 23
  • 37
  • 1
    Wouldn't it potentially be better to use an [std::wstring](https://en.cppreference.com/w/cpp/string/basic_string)? – SimonC Nov 25 '22 at 08:15

1 Answers1

1

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 = { ... };
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621