Зміст курсу
C++ Smart Pointers
C++ Smart Pointers
Constant References And Immutability
A constant reference is a special type of reference that cannot be used to change the value of the referenced object. It provides a level of immutability, i.e. it ensures that the data remains constant within the scope of the reference. Let’s consider an example for better understanding:
main
int main() { int var = 42; // Const reference to value const int& ref = var; // Uncomment to get compilation error: Cannot modify through a const reference // ref = 10; }
In the above code, we create a constant reference by using the const
keyword. Once we have done that, we can’t modify the value of the referenced variable (var
in our case) using that reference. You can test this by uncommenting the ref = 10;
line to get a compilation error.
Benefits of immutability
Immutable code has several advantages. It enhances code readability and simplifies debugging; when someone sees that a variable has been declared to be constant, they can be sure that its value is not going to change anywhere. It also decreases compilation overhead, as the compiler doesn’t have to worry about the value mutations of a constant reference.
Const references as function parameters
One of the most powerful use cases of constant references is passing them as function parameters to avoid unnecessary copies and ensure data integrity. Here’s how it works:
- Since a reference is just an alias of the original variable, there is no copying involved.
- Since we set the reference to constant, the function can’t modify the value of the reference. This ensures that the function only gets read-only access to the variable.
Since the purpose of the displayInfo
function is to display the message, not update it, we use a constant reference to pass message
to it. This way, the function can’t update the value of message
.
As a general rule, try to use constant references across all functions in your code, unless you need to modify the variable inside the function.
Дякуємо за ваш відгук!