بما نعرفه حتى الآن، تحديث متغير بمساعدة دالة أمر مرهق بعض الشيء. فكل وسيط يُمرَّر إلى دالة يُعامَل معاملة نسخة، ولا يغيّر القيمة الأصلية. وبحسب حجم النوع الذي تستخدمه، قد يكون لذلك عواقب وخيمة على أداء الكود.
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 على أنها أسماء مستعارة، فأي تغيير يطرأ عليها ينعكس على المتغير الأصلي.
وتستخدم References علامة العطف (&) في تعريف النوع.
int balance{1000};
int& budget{balance};
int pro_computer_wheels{699};
budget -= pro_computer_wheels;
// budget is now 301;
// balance is also 301;
لا يمكن إعادة تعيين الارتباط، أي تغيير ما يرتبط به reference.
ولا يمكن أن يكون لديك reference غير مهيّأ.
تحتاج References إلى أن تُهيَّأ بمتغير موجود.
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!
voidبفضل references قد لا تحتاج إلى إرجاع قيمة من الدالة إطلاقًا.
وفي هذه الحالة يُستخدم void كنوع للإرجاع.
void increase_power(int& level) {
level += 500;
}
int goku{8700};
increase_power(goku);
// goku's power level?
// It's over 9000!