Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is a cast `int**const` to `const int**const` forbidden

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading