When it comes to function parameters, both references to const and pointers to const are commonly used for passing objects efficiently without allowing modification. However, there are some key differences in their behavior and use cases.
Let's compare them
In this example, we compare the two types:
#include <iostream>
#include <string>
void PrintByRef(const std::string& str) {
std::cout << "Reference: " << str << '\n';
}
void PrintByPtr(const std::string* str) {
if (str) {
std::cout << "Pointer: " << *str << '\n';
} else {
std::cout << "Null pointer\n";
}
}
int main() {
std::string message{"Hello, World!"};
PrintByRef(message);
PrintByPtr(&message);
PrintByPtr(nullptr); // This is valid
// This would be a compile-time error
PrintByRef(nullptr);
}
Reference: Hello, World!
Pointer: Hello, World!
Null pointer
Key differences:
nullptr
to a function expecting a pointer, but not to one expecting a reference.In terms of performance, references and pointers are essentially identical. The compiler typically implements references using pointers under the hood.
Both const T&
and const T*
prevent modification of the pointed-to object:
#include <iostream>
void ModifyByRef(const int& x) {
// x++; // Compilation error
std::cout << "Reference value: " << x << '\n';
}
void ModifyByPtr(const int* x) {
// (*x)++; // Compilation error
if (x) {
std::cout << "Pointer value: " << *x << '\n';
}
}
int main() {
int value{42};
ModifyByRef(value);
ModifyByPtr(&value);
}
Use references when:
Use pointers when:
In modern C++, references are often preferred for their safety and cleaner syntax, unless you specifically need the nullability or rebinding capabilities of pointers.
Answers to questions are automatically generated and may not have been reviewed.
This lesson demystifies references, explaining how they work, their benefits, and their role in performance and data manipulation
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course