1

I can declare foo(const T& var) so that I know var won't be changed.

Equivalent format for pointer would be foo(const T* var)?

In the past I tried those, errors related to iterator/const_iterator irritated me and I just tended to use (T* var) without considering constness.

Are there a good doc for declaring function that enforces contents pointed by a pointer won't change'?

Mysticial
  • 464,885
  • 45
  • 335
  • 332
eugene
  • 39,839
  • 68
  • 255
  • 489

2 Answers2

7

What you have is already a pointer that prohibits the pointee's contents from changing. You can see this by using the "read backwards" rule:

const T* var     <===== left to right from this read

Reading backwards:

var is a pointer to a T that is constant

This is different from

T* const var

Which reads:

var is a constant pointer to a T

The difference here is that the constant is var, not the T; that means you can change the T by dereferencing var but you cannot change what var points to.

And of course you can have both of the above at the same time:

const T* const var
Jon
  • 428,835
  • 81
  • 738
  • 806
0

(from 2 simple variable initialization question)

A really good rule of thumb regarding const:

Read Declarations Right-to-Left.

(see Vandevoorde/Josutiss "C++ Templates: The Complete Guide")

E.g.:

int const x; // x is a constant int
const int x; // x is an int which is const

// easy. the rule becomes really useful in the following:
int const * const p; // p is const-pointer to const-int
int const &p;        // p is a reference to const-int
int * const * p;     // p is a pointer to const-pointer to int.

Ever since I follow this rule-of-thumb, I never misinterpreted such declarations again.

(: sisab retcarahc-rep a no ton ,sisab nekot-rep a no tfel-ot-thgir naem I hguohT :tidE

Equally, you can write your function signatures to this rule:

void foo (int const * const p)

now, p is a const-pointer to const-int. This means that inside the function's body, you cannot let p point to something else, i.e. you can not change the pointer, nor can you change what it is point to.

p being a const-pointer is information that is really only relevant to your function's body, and you should omit this information from the header file:

// foo.h
void foo (int const *p);

then

// foo.cc
void foo (int const * const p) {
    // Here, the const serves you as the implementor as an additional
    // safety gear.
}
Community
  • 1
  • 1
Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130