2

In the code below, why the returned pointer p is allowed to change? If f instead returns "const int *", then the compiler will complain type mis-match error at line "int *p =f()". Why does it do the same for "int * const"?

btw: I know there are memory leaks in the code, but that has nothing to do with the question.

int * const f() {
  return new int(23);
}
int main(){
  int * p=f();
  p= new int(35);
  return 0;
}
user3839198
  • 115
  • 1
  • 10

3 Answers3

3

Because what you are returning is a unmodifiable pointer - not the pointer to unmodifiable data.

Yes, the returned pointer is not modifable - but it will never be modified! You are modifying the different pointer, p - which just happen to have the same value as your unmodifiable (and unnamed) pointer which is now gone - this object is a temporary and forgotten as soon as the statement is completed.

This is why returning const-qualified simple types by value from functions has no sense and actually triggers a warning in some compilers.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • this is true. you should use `int const *` instead of `int * const`. – lolski May 13 '16 at 15:32
  • in addition, `int const * const` will declare a pointer that is both constant in where it points to, as well as the actual value in that location – lolski May 13 '16 at 15:33
0

In the code below, why the returned pointer p is allowed to change?

Because the type of p is int *. Since the pointer is not const, it may be modified. If you want p to not be modifiable, then you must make it const: int * const p

If f instead returns "const int *", then the compiler will complain type mis-match error at line "int *p =f()"

Pointer-to-const is not convertible to pointer-to-non-const. Such conversion is not allowed by the language because it would break const correctness.

Why does it do the same for "int * const"?

I guess you mean to ask "Why does the compiler allow assigning int * const to a int * variable?"

Copying a const object to a non-const object does not break const-correctness. When p is non-const, it's OK to modify it and the const temporary returned by f remains unmodified through it's entire (short) lifetime.

Constness of a temporary is rarely meaningful, and so is returning a top-level const value.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

*const is a constant pointer while const * is a pointer to constant. The latter is immutable value; you can of course assign this value to a variable, like you would write int x = 42;. The former points at an immutable object, so assigning this to a variable that is supposed to point at a mutable object would presumably violate that object's constness.

bipll
  • 11,747
  • 1
  • 18
  • 32