The RC wrapper allocates _mutable_ memory for the reference count on the heap (it has to do that anyway, because it needs to be shared by all instances). As far as I understand, mutating a mutable variable is safe if all users of that variable are aware that it's mutable, _even if it's only reachable through a const pointer_.

This condition is easy to enforce in an RC wrapper, it just has to keep the pointer to the refcount private. To make it easier to prove safety, the pointer needs to be declared as const; all refcount manipulation needs to happen through two small (inlinable) helper methods that do the appropriate cast() magic. The refcount can also be stored next to the payload (better for cache locality anyway), in which case we don't even need to store a const pointer at all, which also means that nobody can accidentally access it in the wrong way.

Reply via email to