Майже всі інші відповіді правильні, але вони пропускають один аспект цього: Коли ви використовуєте додатковий constпараметр у оголошенні функції, компілятор, по суті, ігнорує його. На мить давайте ігноруємо складність того, що ваш приклад є вказівником, і просто скористаємося int.
void foo(const int x);
оголошує ту ж функцію, що і
void foo(int x);
Тільки у визначенні функції є додаткове constзначення:
void foo(const int x) {
// do something with x here, but you cannot change it
}
Це визначення сумісне з будь-якою з декларацій вище. Абонента не хвилює, що xце const- це детальна інформація про реалізацію, яка не є актуальною на сайті виклику.
Якщо у вас є constвказівник на constдані, застосовуються ті самі правила:
// 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
}
Небагато програмістів на C ++ constнамагаються робити параметри , навіть коли вони можуть бути, незалежно від того, чи є ці параметри вказівниками.