Quasi tutte le altre risposte sono corrette, ma mancano di un aspetto: quando si utilizza l'extra constsu un parametro in una dichiarazione di funzione, il compilatore lo ignorerà essenzialmente. Per un momento, ignoriamo la complessità del tuo esempio come puntatore e usiamo semplicemente un file int.
void foo(const int x);
dichiara la stessa funzione di
void foo(int x);
Solo nella definizione della funzione è più constsignificativo:
void foo(const int x) {
// do something with x here, but you cannot change it
}
Questa definizione è compatibile con una delle dichiarazioni precedenti. Al chiamante non interessa che xsia const- questo è un dettaglio di implementazione che non è rilevante nel sito della chiamata.
Se hai un constpuntatore ai constdati, si applicano le stesse regole:
// these declarations are equivalent
void print_string(const char * const the_string);
void print_string(const char * the_string);
// In this definition, you cannot change the value of the pointer within the
// body of the function. It's essentially a const local variable.
void print_string(const char * const the_string) {
cout << the_string << endl;
the_string = nullptr; // COMPILER ERROR HERE
}
// In this definition, you can change the value of the pointer (but you
// still can't change the data it's pointed to). And even if you change
// the_string, that has no effect outside this function.
void print_string(const char * the_string) {
cout << the_string << endl;
the_string = nullptr; // OK, but not observable outside this func
}
Pochi programmatori C ++ si preoccupano di creare parametri const, anche quando potrebbero esserlo, indipendentemente dal fatto che quei parametri siano puntatori.