Prawie wszystkie inne odpowiedzi są poprawne, ale constpomijają jeden aspekt tego: kiedy użyjesz extra parametru w deklaracji funkcji, kompilator zasadniczo je zignoruje. Przez chwilę zignorujmy złożoność twojego przykładu będącego wskaźnikiem i po prostu użyj int.
void foo(const int x);
deklaruje tę samą funkcję co
void foo(int x);
Tylko w definicji funkcji ma dodatkowe constznaczenie:
void foo(const int x) {
// do something with x here, but you cannot change it
}
Ta definicja jest zgodna z którąkolwiek z powyższych deklaracji. Dzwoniącego to nie obchodzix to const- to jest szczegół implementacji, który nie ma znaczenia w miejscu rozmowy.
Jeśli masz constwskaźnik do constdanych, obowiązują te same zasady:
// 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
}
Niewielu programistów C ++ zadaje sobie trud tworzenia parametrów const, nawet jeśli mogą, niezależnie od tego, czy te parametry są wskaźnikami.