C++ Pointers, References, nullptr & Memory Safety Masterclass
Welcome to Phase 8 (Chapter 8): C++ Pointers, References, nullptr & Memory Safety Masterclass! Memory management lies at the core of C++. In Modern C++, raw pointers are used only for non-owning access, nullptr replaces NULL, and resource ownership is managed using smart pointers or RAII.
Core Guidelines for Modern C++ Pointers:
1. Use nullptr: Always initialize pointers to nullptr (C++11) instead of NULL or 0.
2. Avoid raw new / delete: Use smart pointers (std::unique_ptr, std::shared_ptr) or containers for resource ownership.
3. Raw pointers for Non-Owning View: Raw pointers (T*) should only be used to inspect or pass memory owned elsewhere.
4. Prefer References (T&): If a parameter cannot be null, pass by reference (T&) rather than pointer (T*).
#include <iostream>
int main() {
int number{42};
int* ptr{&number}; // Pointer holding address of number
int& ref{number}; // Reference alias for number
std::cout << "Value of number: " << number << "\n";
std::cout << "Address (&number): " << &number << "\n";
std::cout << "Pointer value (ptr): " << ptr << "\n";
std::cout << "Dereferenced (*ptr): " << *ptr << "\n";
std::cout << "Reference (ref): " << ref << "\n\n";
// Modifying through reference
ref = 100;
std::cout << "After ref = 100, number is: " << number << "\n";
// C++11 nullptr check
int* nullPtr{nullptr};
if (nullPtr == nullptr) {
std::cout << "nullPtr is safely checked against nullptr!\n";
}
return 0;
} Q1: What is the difference between a pointer and a reference in C++?
Pointers hold memory addresses, can be nullptr, and can be reassigned. References are non-null aliases that must be initialized upon declaration and cannot be reassigned.
Q2: Why was nullptr introduced in C++11 to replace NULL?
NULL is macro constant 0 (an integer), which caused function overloading ambiguity between f(int) and f(char*). nullptr is a dedicated pointer type (std::nullptr_t).
Q3: What is a dangling pointer?
A pointer referencing memory that has already been deallocated or gone out of scope. Accessing a dangling pointer causes undefined behavior.
Q4: What is pointer arithmetic?
Adding/subtracting integers to a pointer moves its address by multiples of sizeof(T) bytes.
Q5: What is std::unique_ptr?
A smart pointer (C++11) that owns a dynamically allocated object exclusively and automatically deallocates it when going out of scope.