Conteúdo do Curso
C++ Pointers and References
C++ Pointers and References
Reference Use Cases
References provide a powerful mechanism for working with functions. Similar to pointers they enable a direct connection between the caller and the called function, allowing for efficient parameter passing and modification of variables.
Pass-by-reference
This involves passing the actual reference to the variable rather than its value. This allows functions to directly manipulate the original variables.
Look at the example of this implementation, but with the usage of pointers.
main
#include <iostream> void increment(int* num) { (*num)++; } int main() { int num = 5; int* p_num = # increment(p_num); std::cout << "Original value: " << num << std::endl; }
Everything functions properly, but failing to assign an address to the pointer or passing a nullptr to the function could result in errors.
main
#include <iostream> void increment(int& num) { num++; } int main() { int num = 5; increment(num); std::cout << "Original value: " << num << std::endl; }
Reference Variable as Alias
A reference is like a nickname for a variable. It lets you access the variable using a simpler name, making your code easier to understand, while also avoiding unnecessary memory overhead.
main
#include <iostream> int main() { float temperature_outside = 67.2; const float& thermostat = temperature_outside; temperature_outside += 15.7; std::cout << thermostat << std::endl; std::cout << temperature_outside << std::endl; }
Any modifications made to the temperature_outside variable will be reflected in the thermostat reference. However, attempts to alter the value through the thermostat reference itself are restricted due to the use of the const qualifier.
This approach provides a secure method for retrieving temperature readings using the thermostat reference while retaining the ability to update the temperature_outside variable.
Obrigado pelo seu feedback!