本文介绍了有没有可移植的方式来知道uintptr_t是否在stdint.h中定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前置:我想将指针转换为整数类型,例如以检查对准。 uintptr_t 似乎是正确的类型,但

Preamble: I want to convert a pointer to an integer type, e.g. to check alignment. uintptr_t seems to be the correct type, but it is guaranteed only in C, not in C++ (or C++11)

对于以下代码:

#include <stdint.h>
#ifndef I_WONDER_IF_UINTPR_T_IS_DEFINED
  typedef unsigned long uintptr_t;
#endif

template <typename T>
bool isAligned(unsigned char* p) ///Checks alignment with respect to some data type
{
   return !((uintptr_t) p % sizeof(T));
}

template bool isAligned<uint16_t>(unsigned char* p);
template bool isAligned<uint32_t>(unsigned char* p);
template bool isAligned<uint64_t>(unsigned char* p);

2个问题:


  • 是否有一个魔法和保证字,我可以使用 I_WONDER_IF_UINTPR_T_IS_DEFINED

  • 我应该使用<$

生成的程序集(当uintptr_t可用时): a href =http://goo.gl/4feUNK =nofollow> http://goo.gl/4feUNK

Generated assembly (when uintptr_t available): http://goo.gl/4feUNK

注1 :我知道比在C + + 11我应该使用替换 sizeof

注意2:我知道这个讨论:

Note 1: I am aware than in C++11 I should use alignof in place of sizeof
Note 2: I am aware of this discussion: <cstdint> vs <stdint.h>

推荐答案

如果您真的想使用不提供 uintptr_t 当包括< stdint.h> 时,请考虑使用 uintmax_t ,和 static_assert (您已经建立,您可能会在一个愚蠢的设置,所以它可能太小):

If you really want to work with an implementation not providing uintptr_t when including <stdint.h>, consider using uintmax_t instead, and a static_assert for suitability (you already established you might be on a goofy setup, so it might be too small):

#include <stdint.h>
static_assert(sizeof(uintmax_t) >= sizeof(void*), "need a bigger unsigned type.");

// Add code using `uintmax_t` to round-trip data-pointers here

虽然有两个缺点:


  1. uintmax_t uintptr_t ,对重载解析和连结非常重要。

  2. uintmax_t 大于必要。

  1. uintmax_t might not be uintptr_t, important for overload-resolution and linking.
  2. uintmax_t might be bigger than neccessary.

这篇关于有没有可移植的方式来知道uintptr_t是否在stdint.h中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 10:33