【问题标题】:g++ wchar_t string litteral is not of expected type [duplicate]c ++ wchar_t字符串文字不是预期类型[重复]
【发布时间】:2020-08-02 22:00:03
【问题描述】:

(对不起。可能不是最相关的问题......)

根据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

我做对了吗?

【问题讨论】:

  • 提示:使用来自#include &lt;cxxabi.h&gt;abi::__cxa_demangle(typeid(T).name(), 0, 0, 0); 用g++ 对名称进行分解
  • const wchar_t *const wchar_t[N] 是等价的,因为数组只是指针。
  • @Aplet123 完全错误。
  • @KamilCuk 是的!谢谢!
  • @Geoffroy 谢谢,这个不错!

标签: c++ string-literals widechar


【解决方案1】:

这是你使用的auto

auto by value will decay arrays to pointers.

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

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

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

auto& sw = L"foo";

(live demo)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 2018-11-26
    • 2017-06-12
    相关资源
    最近更新 更多