哪些虚拟指针值是好的 [英] Which dummy pointer values are okay

查看:188
本文介绍了哪些虚拟指针值是好的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我长期以来的想法。每次一次,我经常看到人们使用1,或-1作为指针的虚拟值。为了安全地需要一个不同的变量。

This is something that's been on my mind for a long time. Every once so often i see people use 1, or -1 as a dummy value for a pointer. To safe the need of a different variable.

是否可以使用这样的指针?我想,-1是好的。但是也可以使用其他负数?我可以确定1不是一个使用的内存位置?如果是这样,我可以使用内存指针的值。

Is it okay to use pointers like this? I suppose -1 is okay. But is it also okay to use other negative numbers? And can I be sure 1 isn't a used memory location? And if so, up to which value can i use memory pointers.

P.s。我知道存储其他数据,特别是正值的指针,是非常,非常糟糕的做法。但是我只是想知道在任何现实生活中的后果是什么。

P.s. I'm aware storing other data especially positive values in pointers, is very, very bad practice. But I'm just wondering what would be the consequences in any real life situation.

推荐答案

这取决于你的编译器和)操作系统 - 在大多数操作系统上存在永远无效的地址范围。因此,在这样的操作系统上,可以安全地使用诸如magic值这样的地址作为指针,永远不会等于任何有效对象。只要你永远不解引用它们,它们应该是好的 - 即使你解除引用它,操作系统可以定义行为(通常抛出一个特定的信号)。

It depends on your compiler and (mostly) OS -- on most operating systems there are ranges of addresses that can never be valid. So on such an OS, it is safe to use such addresses as 'magic' values for a pointer that will never compare as equal to any valid object. As long as you never dereference them they should be fine -- and even if you do dereference it, the OS may define the behavior (generally throwing a particular signal).

一个更便携的替代方法是创建虚拟全局对象,并使用指针作为您的特殊标记。没有其他有效的对象指针将比较等于虚拟对象指针,并且虚拟对象的额外开销是最小的。

A more portable alternative is to create 'dummy' global objects and use pointers to them as your special tags. No other valid object pointer will ever compare as equal to the dummy object pointer, and the extra overhead for the dummy object is minimal.

这篇关于哪些虚拟指针值是好的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆