Programming
c++ pointers static reference constants
Updated Thu, 21 Jul 2022 11:00:52 GMT

Constant reference to void* pointer


I want to alias a void* variable so I can use it with another name. This would mean I could set pointer (p) to something, and the aliased variable (pp) would also be set to same adress.

For instance:

class foo {
  private:
    static void* p; //I just happen to need this for static variable
    static const void*& pp;
};
//in cpp:
const void*& foo::pp = foo::p;

GCC is complaining:

error: invalid initialization of reference of type 'const void*&' from expression of type 'void*'




Solution

What you are trying to do, i.e. set a const void* & to point to void* seems like it should be legal and harmless enough, but it isn't, and it is illegal for a good reason. Remember that a reference is just an alias to what it is referencing.

Say we could do this:

const void* & foo::pp = foo::p; // illegal as we will see what it leads to

Now suppose that I have this:

const char *x = "Hello world";

As foo::pp is a pointer to const I can point it to x thus:

foo::pp = x; // legal as I can point a const void* to const memory

but p now also points to x because pp is a reference to p.

So now I could do this:

memset( foo::p, 8, 'X' );

which should of course be illegal as I am trying to modify x which is const.

That is why what you are trying to do is not allowed.

void * const& foo::pp = p; would be allowed