您的位置:首页 > 其它

学习 LLVM(7) PointerUnion 类

2012-02-28 00:00 1046 查看
PointerUnion 类当前我知道用在 TinyPtrVector 中做为底层数据存放。简单说明一下。

定义在文件 llvm/include/llvm/[[ADT]]/[[PointerUnion.h]] 中。

== 概述 ==
实现联合保存两种不同的可区分类型的指针,将区分位保存在指针的最低位(NumLowBitsAvailable)。这种方式在空间上是极其节省的,但可以使用非常自然和类型安全的 API。

This implements a discriminated union of two pointer types,
and keeps the discriminator bit-mangled into the low bits of the pointer.
This allows the implementation to be extremely efficient in space, but
permits a very natural and type-safe API.

参见:
* [[PointerUnionTypeSelectorReturn]]
* [[PointerUnionTypeSelector]]
* [[PointerUnionUIntTraits]]
* [[PointerIntPair]]

(注:对它们的描述略)

== 实现机理 ==
模板类 PointerUnion 概要如下:

<syntaxhighlight lang="cpp">
template <PT1, PT2> class PointerUnion {
PointerIntPair<...> Val; // 注1

PointerUnion() // 多种构造函数,注2
isNull() -- 如果指针为 null 则返回 true,和类型无关
is<PT1>(), is<PT2>() -- 返回 true 如果指针是类型 PT1, PT2
get<PT1>(), get<PT2>() -- 返回指针
// 其它函数略
}
</syntaxhighlight>

* 注1: PointerIntPair<void*, 1, ...> 参见 [[PointerIntPair]],表示一个指针+1位的整数。
* 注2:当构造为 PT1* 时,Val.int = 0;当指针为 PT2* 时,Val.int = 1

== 评述 ==
在一个 void* 空间中保存两种类型的指针,以指针的低位 bit 来保存指针类型,看起来很麻烦。
用起来也要小心,用途不多的话,还不如不要这么麻烦,多放一个字节来保存类型信息也很好的。

实现的 PointerUnion3, PointerUnion4 与此类似,都十分辛苦但没有必要??

参见:
* [[TinyPtrVector]]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LLVM