Results for “Ownership & optional values”
Small, practical examples. Search by task or narrow things down below.
Observe shared ownership without extending its lifetime
C++: A weak_ptr can be locked while an owner exists and becomes expired after the last owner is released.
C++✓ Tested
Represent an absent result with optional
C++: value_or supplies a default without requiring a sentinel inside the value domain.
C++✓ Tested
Share ownership with a counted smart pointer
C++: Copies of shared_ptr keep the owned value alive until the last owner is released.
C++✓ Tested
Transfer unique ownership with move
C++: Moving a unique_ptr leaves the source empty and gives ownership to the destination.
C++✓ Tested
Apply an operation to a variant’s active value
C++: A generic visitor lets the compiler check behavior for every possible alternative.
C++✓ Tested
Capture configuration by value in a callable
C++: A value capture retains the value from lambda creation even if the original variable changes later.
C++✓ Tested
Own one dynamically allocated value with unique_ptr
C++: make_unique allocates a value whose lifetime is tied to its owning smart pointer.
C++✓ Tested
Read a variant only when it holds the expected type
C++: get_if returns a null pointer rather than throwing for another active alternative.
C++✓ Tested
Run cleanup through a scoped destructor
C++: A stack object’s destructor runs when its scope exits, including normal exception unwinding.
C++✓ Tested
Store a reference in a standard container
C++: reference_wrapper preserves reference semantics while behaving like a copyable container element.
C++✓ Tested
Keep an optional value only when valid
Keep an optional value only when valid in a complete Rust program using the standard library.
Rust✓ Tested
Transform an optional value
Transform an optional value in a complete Rust program using the standard library.
Rust✓ Tested