在指针中存储无符号整数

Kaa*_*reZ 0 c++ pointers casting unsigned-integer

我正在构建一个八叉树数据结构,为了节省最终节点的内存,我希望将值直接存储在指针中,而不是必须创建一个容纳8个子节点的对象.

我的数据类型是uint32_t,这意味着指针有足够的位来将其保存在x86或amd64上.

那么如何在x86或amd64指针中存储无符号32位整数?

伪代码:

uint32_t i = 123;
Octree* ptr = i;
uint32_t ii = ptr;
std::cout << ii << std::endl; //Prints 123
Run Code Online (Sandbox Code Playgroud)

这怎么可能?

Mat*_*lia 5

不允许以可移植的方式直接指针中存储无符号整数,但您可以:

  • 反过来:你可以将指针存储在无符号整数中; 具体而言,uintptr_t标准明确保证足够大,以使指针在往返中幸存;
  • 用一个union:

    union NodePtr {
        Octree *child;
        uint32_t value;
    }
    
    Run Code Online (Sandbox Code Playgroud)

    这里childvalue共享相同的存储位置,和你被允许只从一个地方你上次写读; 当您在使用的终端节点时value,否则使用child.