Topic 16 of 27 · Beginner
How do references differ from pointers in an API?
A reference expresses an alias to an existing object and must be initialized. A pointer is a value that may be null and can be reseated, so it can express optional access.
C++20; compile with g++ -std=c++20.
Detailed answer
A reference expresses an alias to an existing object and must be initialized. A pointer is a value that may be null and can be reseated, so it can express optional access.
Use const T& for read-only access to an existing large object and T* when absence is meaningful. Neither a reference nor a raw pointer implies ownership.
References can still dangle if the referred object has died. Do not return a reference to a local object or assume the type guarantees a valid lifetime.
Internal working
References are implemented according to the ABI; the language specifies aliasing behavior, not a mandatory storage representation.
Practical scenario
A lookup may fail; returning a reference is inappropriate unless failure is signaled separately. A pointer can return nullptr.
#include <iostream>
void twice(int& x){x*=2;}
int main(){int x=3;twice(x);std::cout<<x<<"\n";}Common mistakes
- Returning references to locals.
- Assuming a raw pointer owns its target.
Key takeaways
- Express optionality explicitly.
- Separate access from ownership.
- Check lifetimes.
Follow-up challenges
- When would std::optional be preferable?
- How can a const reference extend a temporary lifetime?