Con le conoscenze che abbiamo ora, aggiornare una variabile con l'aiuto di una funzione è un po' macchinoso. Ogni argomento di una funzione viene trattato come una copia e non modifica il valore originale. A seconda della dimensione del tipo, questo può avere conseguenze serie sulle prestazioni del codice.
int adjust_salary(int base, int kids) {
return base + kids * 500;
}
int now_a_mother_of_twins{2500};
adjust_salary(now_a_mother_of_twins, 2);
// now_a_mother_of_twins is still 2500
now_a_mother_of_twins = adjust_salary(now_a_mother_of_twins, 2);
// now_a_mother_of_twins is now 3500
References si possono vedere come alias: le modifiche hanno un effetto sulla variabile originale.
References usano una e commerciale (&) nella dichiarazione del tipo.
int balance{1000};
int& budget{balance};
int pro_computer_wheels{699};
budget -= pro_computer_wheels;
// budget is now 301;
// balance is also 301;
La riassegnazione (cambiare l'associazione di un reference) non è possibile.
Non si può avere un reference non inizializzato.
I References devono essere inizializzati con una variabile esistente.
int main_acc{1'000'000};
int side_acc{-20};
int& savings{main_acc};
// => main_acc and savings are 1'000'000
// try to reseat savings to use main account
savings = side_acc;
// savings and main_acc are now -20
// as this uses the **value** of side_acc
savings += 20;
// savings and main_acc are now 0, side_acc is stil -20
int& future_budget;
// => compiler error, reference must be bound!
voidCon la potenza dei references potresti non aver bisogno di restituire alcun valore da una funzione.
In questo scenario, void viene usato come tipo di ritorno.
void increase_power(int& level) {
level += 500;
}
int goku{8700};
increase_power(goku);
// goku's power level?
// It's over 9000!