g++ wchar_t 字符串文字不是预期的类型

g++ wchar_t string litteral is not of expected type

(抱歉。可能不是最相关的问题...)

根据https://en.cppreference.com/w/cpp/language/string_literal
""" 宽字符串文字。L"..." 字符串文字的类型是 const wchar_t[N] """

然而,在这种情况下,g++ 似乎选择了 const wchar_t* :

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";

在 GCC 5.4.0 上给出以下输出:

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

我做对了吗?

是你使用auto.

auto by value will decay arrays to pointers.

typeid 和宽字符串文字在这里并不严格相关。

您的字符串文字确实具有 const wchar_t[4] 类型,并且(与评论部分中的声明相反)这 const wchar_t* 相同。

根据链接的答案,我们可以通过切换到引用类型来抑制这种情况(尽管坦率地说,ew):

auto& sw = L"foo";

(live demo)

尽量不要无缘无故地到处使用auto。它做这样的事情,并对你隐藏结果。仅在必须(例如 lambda 声明)或收益超过任何潜在风险(例如迭代器声明)时才使用它。