How are const and auto const applied to pointers?

I tried some code and wonder how a constqualifier in C ++ applies to pointer types when used auto.

int main()
{
  int foo = 1;
  int bar = 2;

  //Expected: const int * ptr_to_const_int = &foo;
  const auto ptr_to_const_int = &foo;

  //Expected: int * const const_ptr_to_int = &foo;
  auto const const_ptr_to_int = &foo;


  *ptr_to_const_int = 3; //Thought this would error
  //ptr_to_const_int = &bar; This does error.
  *const_ptr_to_int = 3;

  return 0;
}

I understand that there is a similar question asking the question whether they are the same. I ask what exactly is the rule that applies to the deduction of the type of the trailing pointer.

+4
source share
1 answer

const auto, , int * const, auto int *. , , , auto const const auto, , , int const const int .

:

template<typename T>
using pointer = T*;

pointer<int> ptr_to_int = new int;
const pointer<int> const_ptr_to_int = new int;
pointer<const int> ptr_to_const_int = new int;
const pointer<const int> const_ptr_to_const_int = new int;

pointer<int> const const_ptr_to_int2 = new int;
pointer<int const> ptr_to_const_int2 = new int;
pointer<const int> const const_ptr_to_const_int2 = new int;

pointer<int const> const const_ptr_to_const_int3 = new int;

, - , , ++. , , const, . , "--" , : (, , auto), .

, , , , using typedef pointer<T>, , , , , , const pointer<int>, , int *const. , :

int * a_ptr, b_ptr, c_ptr; //Oops! We meant b_ptr and c_ptr to also be pointers, but
//they ended up being regular ints!

pointer<int> a_ptr, b_ptr, c_ptr; //All of these are pointers, as we expected them to be

auto , , , ( ), const , , .

+7

Source: https://habr.com/ru/post/1689022/


All Articles