Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `const T* const` mean?

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?

like image 302
user997112 Avatar asked Nov 25 '11 22:11

user997112


People also ask

What does const mean in coding?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

What is int const * ptr?

int const* is pointer to constant integer This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn't be changed.

What is const pointer in C++?

A constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the address will remain constant. Therefore, we can say that if a constant pointer is pointing to some variable, then it cannot point to any other variable.

What is const modifier?

Const means simply, as you described, that the value is read-only. constant expression, on the other hand, means the value is known compile time and is a compile-time constant.


2 Answers

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.

like image 175
Fred Foo Avatar answered Oct 15 '22 15:10

Fred Foo


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.

like image 43
Andrew Rasmussen Avatar answered Oct 15 '22 14:10

Andrew Rasmussen