q0987
q0987

Reputation: 35982

why use the underlying type of an enum class to define a variable?

I saw the following comment in some code.

 * The implementation uses custom pointer types to save space, and
 * to preserve addresses if the underlying container is resized.
 * For instance we define `enum class id_t : uint32_t {}`
 * instead of (id *)

Question> Why use enum class type can preserve address?

Upvotes: 0

Views: 72

Answers (1)

John Zwinck
John Zwinck

Reputation: 249153

This technique is sometimes known as "relative addressing" or "offset pointers." For example, if you have an array:

int arr[1000];

And you want to store two locations in it, you could do:

int *x = &arr[40];
int *y = &arr[100];

But instead you do:

uint32_t x = 40;
uint32_t y = 100;

Then to dereference one of these "pointers" you say arr[x] instead of *x.

To avoid having to keep arr around, you can encapsulate the offsets:

template <size_t N>
class offsets {
public:
    int& operator[](size_t idx) const { return _arr[_off[size_t]]; }

private:
    int* _arr;
    std::array<uint32_t, N> _off;
}

And now you have saved space on a 64-bit platform, because you store 64+32*4 = 192 bits, instead of 256 bits for four regular pointers.

You also don't need to update them if _arr changes (e.g. to grow or shrink the array). This could be a meaningful optimization if the number of stored offsets is large.

Upvotes: 1

Related Questions