The following is allowed:
int * const p1 = nullptr;
auto p2 = static_cast< const int * const >( p1 );
In my understanding p1
is a "const-ptr to int", which is casted to a
"const-ptr to const-int".
Why is the following forbidden
int * * const pp1 = nullptr;
auto pp2 = static_cast< const int * * const >( pp1 );
In my understanding pp1
is a "const-ptr to ptr to int" which shall be casted to a "const-ptr to ptr to const-int". Thus I am adding const
, so I would think it is allowed.
Even though it looks like you're only adding const
, you can use the resulting pointer to remove constness (a const_cast
in disguise). Observe:
int **const pp1 = nullptr;
auto pp2 = (const int **const)pp1;
const int x = 42;
*pp2 = &x;
**pp1 = 43; // Modifying `x` = undefined behavior.
Note that, on the other hand, casting to const int *const *
(and const int *const *const
) is allowed.