C++ std::optional vs Pointers: Representing "No Value" Safely
이 글의 핵심
Guide to std::optional vs pointers: when optional wins, when pointers are required, and performance notes.
When you need owning heap storage instead of optional, compare shared_ptr vs unique_ptr.
Introduction: “How should I represent null?”
C++ offers nullptr pointers and std::optional<T> (C++17) for “maybe no value,” with very different safety and cost profiles.
This article covers:
- optional vs pointers
- Type safety
- Performance
- Scenarios
1. Comparison
| Aspect | std::optional | T* |
|---|---|---|
| Storage | Usually inline | Address-sized |
| Ownership model | Owns value state | Aliases external object |
| Absent value | std::nullopt | nullptr |
| Safety | harder to “forget” checks (value()/bad_optional_access) | easy to dereference nullptr |
2. Type safety
optional encourages explicit checks: has_value(), value_or(), value() (throws if empty).
3. Performance
Microbenchmarks often show optional vs stack pointer checks in the same ballpark; heap pointers add allocation noise.
4. Scenarios
- optional:
optional<int>return from parsing; optional function parameters - pointers: virtual dispatch; pointing into existing storage
- smart pointers: shared ownership (
shared_ptr) when needed
Summary
| Situation | Prefer |
|---|---|
| Maybe-missing return by value | optional |
| Polymorphic object | pointer/unique_ptr |
| Large object without copying | pointer/unique_ptr/out-param |
Related reading
- shared_ptr vs unique_ptr
- nullptr guide
Keywords
std::optional, optional vs pointer, C++17, null safety
Related posts
- variant vs union
- any vs void*