Search code examples
c++castingstatic-cast

casting const pointers between different types


I have a C++ function where one of the input parameters is of type char const* buffer. The way I understand it is that the underlying values of this array can be changed but the pointer itself cannot be moved to point to something else.

Now what I want to do is reinterpret this array as unsigned short and do some manipulations. So, I do something like:

char const * current = &buffer[currentLine]; // Points to some location
unsigned short * const values = static_cast<unsigned short * const>(current);
// Change some of these values

This results in invalid cast from top char * const to type short unsigned int * const.

How should this casting be performed?


Solution

  • The way I understand it is that the underlying values of this array can be changed but the pointer itself cannot be moved to point to something else.

    Nope. It means that you cannot change the entity this pointer points too, but you are able to change a pointer itself. To forbid changing the pointer you have to make the pointer itself const:

    const char* const buffer;
                ^^^^^
    

    How should this casting be performed?

    The casting should be performed with reinterpret_cast.

    Only the following conversions can be done with reinterpret_cast, except when such conversions would cast away constness or volatility.

    ...

    5) Any pointer to object of type T1 can be converted to pointer to object of another type cv T2.

    So you have to write:

    unsigned short * const values = reinterpret_cast<unsigned short * const>(current);
    

    or even:

    decltype(auto) values = reinterpret_cast<unsigned short * const>(current);
    

    Finally, static_cast is not applicable here because you try to perform a cast between different unrelated pointer types.