在 C++ 中确定指针限制的惯用方法是什么?

发布于 2024-09-09 17:42:54 字数 116 浏览 1 评论 0原文

我想在编译时知道指针类型的值范围。 limits.h 仅指定纯数字类型的最大值和最小值。我不想使用硬编码常量,并且我不喜欢使用 sizeof(foo*) 计算最大值。

I'd like to know at compile-time the range of values for a pointer type. limits.h only specifies maximums and minimums for pure number types. I don't wish to use hard-coded constants, and I prefer not to compute a max using sizeof(foo*).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

羅雙樹 2024-09-16 17:42:54

我相信我会使用 intptr_t。它被定义为可以保存指针值的整数,因此 intptr_t 的最小/最大值应该起作用。

可能大于实际指针的值。但是从您对只需要最小/最大值的类的解释来看,我不认为您需要完全准确。

I believe I would use intptr_t. It is defined to be the integer that can hold a pointer value, so the min/max values of intptr_t should work.

It might be larger than the values of an actual pointer. But from your explanation of a class that just needs min/max values, I don't believe that you need complete accuracy.

∞琼窗梦回ˉ 2024-09-16 17:42:54

指针不是数字。特别是,它们不是绝对有序的 - 给定两个随机指针 pq,你不能将一个指针从另一个指针中减去并得到一个有意义的结果 - 它是 UB,除非它们两者都指向同一个对象(malloc 内存块、静态或自动对象等)。因此,指针允许范围的概念在标准 C++ 中是没有意义的。

Pointers are not numbers. In particular, they're not absolutely ordered - given two random pointers p and q, you cannot subtract one from another and get a meaningful result - it is U.B., unless they both point to the same object (malloc memory block, static or automatic object, etc). So the concept of a permitted range of pointers is meaningless in Standard C++.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文