OK to do bit-packing with GC pointers?

Ben Jones fake at fake.fake
Fri Jul 22 16:50:44 UTC 2022


I'm looking to store a pointer to one of 2 unrelated (no 
inheritance relationship) classes and use the LSb to track which 
type I have.  Is this going to cause any problems with the GC?  
For one of the classes I'll have a "pointer" to 1 byte past the 
start of the object.  It seems like std.bitmanip.taggedClassRep 
does something similar, so I assume it's OK, but wanted to double 
check.

Here's the type:

```
struct EitherClass(C1, C2) if (is(C1 == class) && is(C2 == 
class)){


     private size_t data;

public:
     @safe:
     @nogc:
     nothrow:

     this(C1 c1) @trusted {
         data = cast(size_t)(cast(void*)(c1));
     }

     this(C2 c2) @trusted {
         data = cast(size_t)(cast(void*)(c2));
         data |= 1;
     }

     typeof(this) opAssign(C1 c1) @trusted {
         data = cast(size_t)(cast(void*)(c1));
         return this;
     }

     typeof(this) opAssign(C2 c2) @trusted {
         data = cast(size_t)(cast(void*)(c2));
         data |= 1;
         return this;
     }

     bool holds(C)() const if(is(C == C1) || is(C == C2)){

         static if(is(C == C1)){
             return (data & 1) == 0;
         } else {
             return (data & 1) != 0;
         }
     }

     auto get(C)() const @trusted if(is(C == C1) || is(C == C2)) {
         static if(is(C == C1)){
             assert(holds!C1);
             return cast(C1)(cast(void*)(data));
         } else {
             assert(holds!C2);
             return cast(C2)(cast(void*)(data & ~(1UL)));
         }
     }

}

```


More information about the Digitalmars-d-learn mailing list