0

For example:

void test() {
    int* a = new int(1);
    int ** ap = &a;

    int const * b = new int(1);
    int const ** bp = &b;
    b = a;
//  bp = ap; //error

    //deletes
}

Why b = a is accepted while bp = ap rejected? How if I really want the effect of bp = ap? Is it an acceptable practice?

  • 1
    `b = a` is a promise that you won't modify the int through `b`. `bp = ap` would be a promise that you won't modify the int through `a`, which the type of `a` does not guarantee. I think that violates aliasing rules but I'm not sure enough to quote chapter and verse. – Goswin von Brederlow May 31 '22 at 21:20

1 Answers1

1

Why b = a is accepte

Because pointers to "non-const T" are implicitly convertible to pointers to "const T". The result of the conversion still points to an object of type T; only the cv-qualifier of the type differs.

while bp = ap rejected?

Because a pointer to "pointer to non-const T" is not implicitly convertible to a pointer to a pointer to "pointer to const T". The result would be a pointer to an object of different type (const T* vs T*), both of which happen to have the same cv-qualifier (non-const).

How if I really want the effect of bp = ap

This depends on what kind of analogy you are wanting. You can create a pointer to const, and then point bp to that:

int const * ap_const = &a;
bp = &ap_const;

But you should really think about why you want the effect. Perhaps it isn't what you need and you should want something else.


Sidenote 1: Dynamically allocating a singular int is quite rarely useful. Avoid unnecessary dynamic allocation.

Sidenote 2: When you do need dynamic allocation, avoid using bare owning pointers such as in the example. Prefer RAII containers and smart pointers instead.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 2
    C++ FAQ [Why am I getting an error converting a `Foo**` → `const Foo**`?](https://isocpp.org/wiki/faq/const-correctness#constptrptr-conversion) – Eljay May 31 '22 at 21:52
  • @Swift-FridayPie [conv.qual] section of the standard would be the official reference. It describes when two types are similar. The standard wording is confusing to mortals, so simplest description is to just drop the top-level const (more generally, cv) and if everything else is same, then the types are similar regardless of that dropped const. (And then special cases with arrays). – eerorika May 31 '22 at 21:55