Search code examples
c++string-literalswidechar

g++ wchar_t string litteral is not of expected type


(sorry. might not be the most relevant question...)

According to https://en.cppreference.com/w/cpp/language/string_literal:
""" Wide string literal. The type of a L"..." string literal is const wchar_t[N] """

however, g++ seems to be choosing const wchar_t* in this case :

auto sw = L"foo";
cout << "type : " << typeid(sw).name() << " >" << sw << "<\n";
cout << "   type : " << typeid( const wchar_t * ).name() << " | type : " << typeid( const wchar_t [] ).name() << "\n";

which gives the following output on GCC 5.4.0:

type : PKw >0x401470<
   type : PKw | type : A_w

Did I get it right ?


Solution

  • It's your use of auto.

    auto by value will decay arrays to pointers.

    typeid and wide string literals are not strictly relevant here.

    Your string literal indeed has type const wchar_t[4], and (contrary to claims in the comments section) this is not the same as const wchar_t*.

    Per the linked answer, we can inhibit this by switching to a reference type (although, frankly, ew):

    auto& sw = L"foo";
    

    (live demo)

    Try not to use auto all over the place for no reason. It does things like this, and hides the result from you. Use it only when you must (e.g. lambda declarations) or when the benefits outweight any potential risk (e.g. iterator declarations).