Pointers and References
Pointers and References
Understand addresses, indirection, aliasing, and when references are safer than raw pointers.
Pointers and References
Understand addresses, indirection, aliasing, and when references are safer than raw pointers.
int value = 10;
int& ref = value;
ref = 20;
Changing ref changes value because they refer to the same object.
int value = 10;
int* ptr = &value;
*ptr = 20;
Use nullptr, not NULL or 0.
int* ptr = nullptr;
void increment(int& x) {
++x;
}
Pointers and references often mean "I can access this object", not "I own it". In modern C++, ownership should usually be represented by:
std::unique_ptrstd::shared_ptr when shared ownership is truly requiredconst correctnessvoid print(const std::string& text);
void mutate(std::string& text);
When you add const accurately, both humans and the compiler get a stronger picture of what a function may change.
Modern C++ often replaces raw pointer-and-length pairs with std::span<T> and raw C strings with std::string_view.