What does `const T * const` mean?

I read an example C ++ template, and part of the template signature confused me.

I am reading this correctly:

const T* const foo; 

Is foo a const* up to a const T ?

+4
source share
7 answers

Yes, this is a constant pointer to the constant T Ie, you can neither change the pointer, nor what it points to.

const T* forbid you to change everything that the pointer indicates, but allows you (within the language) to check the value in *(foo+1) and *(foo-1) . Use this form when you pass pointers to immutable arrays (for example, the C string you only have to read).

T * const means that you can change the value of T pointed to by foo , but you cannot change the pointer itself; therefore you cannot say foo++; (*foo)++ foo++; (*foo)++ , because the first statement will increment (change) the pointer.

T * will give you complete freedom: you get a pointer to an array, and you can check and modify any member of this array.

+7
source

Yes, foo is a constant pointer to the constant T.

+1
source

Yes; this is exactly what it means.

Since there is always little confusion about const when using pointers, the following possibilities are possible:

  • const T * aConstant

    means aConstant - variable pointer on constant T

  • T const * aConstant

    does the same thing.

  • T * const aConstant

    declares that aConstant is a constant pointer and

  • T const * const aConstant (or const T * const aConstant )

    declares a constant constant T pointer constant T

+1
source

This is const-pointer-const-const. Therefore, if T was int, then the array is a pointer to int, which is const in two ways:

pointer-to-const: the value that the pointer points to cannot be changed (or points to const int) const: the memory address stored in the pointer cannot change

It is also the same as T const * const array

See the wiki on const correctness .

+1
source

Yes, it is, I think the name var (const) is what haunts you.

0
source

Yes.


 const T* 

does const array elements ... at least with respect to foo .

 foo[0] = T(); // Illegal! foo[1] = T(); // Illegal! foo[2] = whatever; // Illegal! 

 const 

makes foo constant pointer. Therefore it is illegal:

 foo = &some_array; 

Variable

 foo 

... if you do not know what it is, you should seriously consider attending preschool.

0
source

Yes, it just means that you not only cannot change what foo points out, but you also cannot change the value of foo itself to point to some other instance of T

0
source

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


All Articles