【问题标题】:Be careful: the "unsigned" specifier changes the size of the wchar_t type in Visual Studio注意:“无符号”说明符会更改 Visual Studio 中 wchar_t 类型的大小
【发布时间】:2020-11-07 16:57:38
【问题描述】:

在 Visual Studio 中将 unsigned 说明符添加到 wchar_t 类型会将类型大小从 2 个字节更改为 4 个字节。

通过在 Visual Studio 2008 或最新的 Visual Studio 2019 中运行以下两行代码:

    cout << "wchar_t: " << sizeof(wchar_t) << endl;
    cout << "unsigned wchar_t: " << sizeof(unsigned wchar_t) << endl;

对于wchar_t,您会收到2,对于unsigned wchar_t,您会收到4,并且只有警告C4076('unsigned': cannot be used with type 'wchar_t')。

预期的行为是保留 2 字节大小。 documentation says 没有改变大小,只是告诉使用编译器选项使 whcar_t 成为 unsigned short 的 typedef:

Microsoft 特定:默认情况下,wchar_t 是本机类型,但您可以使用 /Zc:wchar_t- 使 wchar_t 成为 unsigned short 的 typedef。 __wchar_t 类型是 Microsoft 特有的原生 wchar_t 类型的同义词。

这可能是启用“将警告视为错误”编译器选项并遵循零警告规则的另一个原因。

至少对于新项目。不幸的是,在处理遗留代码时,要遵循这条规则可能非常困难甚至不可能。

【问题讨论】:

    标签: c++ visual-c++ sizeof


    【解决方案1】:

    我认为visual studio在这里是正确的,unsigned wchar_t(或signed wchar_t)没有provision in the standard,所以编译器如何处理它取决于编译器。虽然错误会很好(由 GCC 和 Clang 提出),但警告也是可以的。

    大概这 4 个字节是因为 Visual Studio 必须决定丢弃 unsignedwchar_t 之一并决定丢弃 wchar_t 留下一个 unsigned int

    【讨论】:

      猜你喜欢
      • 2011-01-20
      • 2020-07-05
      • 2019-12-08
      • 2021-12-27
      • 2012-08-10
      • 2015-01-21
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      相关资源
      最近更新 更多