gpt4 book ai didi

c++ - intptr_t 是 uintptr_t 的签名拷贝吗(反之亦然)?

转载 作者:可可西里 更新时间:2023-11-01 15:41:30 29 4
gpt4 key购买 nike

我正在为 add_signed MPL 类开发一些测试,将类型转换为其已签名的对应项。定义如下:

template<class T>
struct add_signed {
typedef T type;
};

template<>
struct add_signed<std::uint8_t> {
typedef std::int8_t type;
};

template<>
struct add_signed<std::uint16_t> {
typedef std::int16_t type;
};

template<>
struct add_signed<std::uint32_t> {
typedef std::int32_t type;
};

template<>
struct add_signed<std::uint64_t> {
typedef std::int64_t type;
};

在对不同类型进行测试时,我注意到以下计算结果为真:

std::is_same<add_signed<uintptr_t>::type, intptr_t>::value  // true

与 add_unsigned MPL 类类似,以下代码的计算结果为真:

std::is_same<add_unsigned<intptr_t>::type, uintptr_t>::value  // true

我的编译器是 MSVC 2010。

所以问题是 - 我们是否可以假设在所有(正常的)编译器中签署 intptr_t 将生成 uintptr_t,反之亦然?

最佳答案

类型 intptr_tuintptr_t 在 ISO/IEC 9899:1999 (C99) 中是可选的,但是其中一个实现的地方,另一个也是可选的。所有有符号类型都有一个相同大小的无符号对应物,反之亦然。

§7.18.1 Integer types

When typedef names differing only in the absence or presence of the initial u are defined, they shall denote corresponding signed and unsigned types as described in 6.2.5; an implementation providing one of these corresponding types shall also provide the other.

...

§7.18.1.4 Integer types capable of holding object pointers

The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:

intptr_t

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:

 uintptr_t

These types are optional.

请注意,在 C 标准的意义上,函数不是对象; C 标准不保证 uintptr_t 可以保存函数指针。

幸运的是,POSIX救援步骤:它确实要求对象指针和函数指针的大小相同。

2.12.3 Pointer Types

All function pointer types shall have the same representation as the type pointer to void. Conversion of a function pointer to void * shall not alter the representation. A void * value resulting from such a conversion can be converted back to the original function pointer type, using an explicit cast, without loss of information.

Note:

The ISO C standard does not require this, but it is required for POSIX conformance.

关于c++ - intptr_t 是 uintptr_t 的签名拷贝吗(反之亦然)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10398304/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com