Reputation: 30615
I was reading a C++ template example, and part of the template signature confused me.
Am I reading this correctly:
const T* const foo;
Is foo
a const*
to a const T
?
Upvotes: 10
Views: 8604
Reputation: 1411
simply parse it like this
const<ptr<const<T>>> foo
although it is illegal, but I think everyone can grasp its essence.
Upvotes: 0
Reputation: 363547
Yes, it's a constant pointer to a constant T
. I.e., you can neither modify the pointer, nor the thing it points to.
const T*
would only forbid you to modify anything the pointer points to, but it allows you (within the bounds of the language) to inspect the value at *(foo+1)
and *(foo-1)
. Use this form when you're passing pointers to immutable arrays (such as a C string you're only supposed to read).
T * const
would mean you can modify the T
value pointed to by foo
, but you cannot modify the pointer itself; so you can't say foo++; (*foo)++
because the first statement would increment (modify) the pointer.
T *
would give you full freedom: you get a pointer into an array, and you can inspect and modify any member of that array.
Upvotes: 13
Reputation: 27201
Yes.
const T*
makes the elements of the array const
... at least, as far as foo
is concerned.
foo[0] = T(); // Illegal!
foo[1] = T(); // Illegal!
foo[2] = whatever; // Illegal!
const
makes foo
a constant pointer. Therefore, this is illegal:
foo = &some_array;
The variable
foo
...if you don't know what this is, you should seriously consider going to preschool.
Upvotes: 1
Reputation: 7164
Yes; that is exactly what it means.
Since there is always a little confusion about const
when using pointers, there are the following possibilities:
const T * aConstant
means aConstant
is a variable pointer to a constant T
.
T const * aConstant
does exactly the same.
T * const aConstant
declares that aConstant
is a constant pointer to a variable T
and.
T const * const aConstant
(or const T * const aConstant
)
declares a constant pointer to a constant T
.
Upvotes: 3
Reputation: 20726
Yes, it just simply means that not only can't you change what foo
points to, but you also can't change the value of foo
itself so that it points to some other T
instance.
Upvotes: 0
Reputation: 15099
This is a const pointer-to-const T. So if T was an int, then array is a pointer to an int that is const in two ways:
pointer-to-const: the value that the pointer is pointing to cannot be changed (or pointing to const int) const pointer: the memory address stored in the pointer cannot change
This is also the same as T const * const array
See wiki on const correctness.
Upvotes: 2
Reputation: 670
Yes it is, i think name of var(const) is what stumbles you.
Upvotes: 0