c++ - unsigned long 的类型不同于 Windows 上的 uint32_t 和 uint64_t (VS2010)

标签 c++ visual-c++ visual-c++-2010

在 Windows 7、32 位的 Visual Studio 2010 上,unsigned long 似乎是与 uint32_t 和 uint64_t 截然不同的类型。看下面的测试程序:

#include <stdint.h>
#include <stdio.h>

template<class T, class U>
struct is_same_type
{
    static const bool value = false;
};
template<class T>
struct is_same_type<T, T>
{
    static const bool value = true;
};

#define TO_STRING(arg)        TO_STRING_IMPL(arg)
#define TO_STRING_IMPL(arg)   #arg

#define PRINT_SAME_TYPE(type1, type2) printf("%s (size=%d) %s %s (size=%d)\n", \
    TO_STRING(type1), int(sizeof(type1)), \
    is_same_type<type1, type2>::value ? "==" : "!=", \
    TO_STRING(type2), int(sizeof(type2)))


int main(int /*argc*/, const char* /*argv*/[])
{
    PRINT_SAME_TYPE(uint32_t, unsigned long);
    PRINT_SAME_TYPE(uint64_t, unsigned long);
    return 0;
}

我希望它能打印出来

uint32_t (size=4) != unsigned long (size=8)
uint64_t (size=8) == unsigned long (size=8)

(我在 x86_64 Linux 上得到)或

uint32_t (size=4) == unsigned long (size=4)
uint64_t (size=8) != unsigned long (size=4)

当然假设 long 不超过 64 位。

然而,在 Windows 上,我感到莫名其妙

uint32_t (size=4) != unsigned long (size=4)
uint64_t (size=8) != unsigned long (size=4)

这意味着有两种不同的 32 位无符号类型。这是 C++ 标准允许的吗?或者这是 Visual C++ 编译器中的错误?

最佳答案

There are two distinct 32-bit, unsigned types

是的,有。 intlong都用32位表示。

Is this allowed by the C++ standard?

是的。规范规定 (C++11 §3.9.1[basic.fundamental]/2):

There are five standard signed integer types : signed char, short int, int, long int, and long long int. In this list, each type provides at least as much storage as those preceding it in the list.

For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type...each of which occupies the same amount of storage and has the same alignment requirements as the corresponding signed integer type

请注意,尽管 intlong 由相同的位数表示,但它们仍然是不同的类型(因此,例如,它们被区别对待在重载决议期间)。

关于c++ - unsigned long 的类型不同于 Windows 上的 uint32_t 和 uint64_t (VS2010),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11611467/

相关文章:

c++ - MS visual studio IDE下如何使用g++编译器

c++ - "Multi-byte Character Set"当前的现代术语是什么

visual-studio - 使用标准 #ifndef MS-VC++ 覆盖 #pragma 一次

c++ - 堆上非常大的数组 (Visual C++)

c++ - '_ITERATOR_DEBUG_LEVEL' : value '0' doesn't match value '2' 检测到不匹配

c++ - 遍历数组的简单任务。这些解决方案中哪个最有效?

c++ - 以下代码有什么问题

c++ - clang 和 gcc 中是否有 Visual C++ __declspec (属性声明属性)的替代方案?

c++ - 如何在重用 std::stringstream 变量时避免使用 std::stringstream.str() 和 std::stringstream.clear() ?

C++ 模板 friend 奇怪的行为