Module lessons (4/4)
Zero-Copy Views: std::string_view and std::span
Pass non-proprietary views on contiguous strings and buffers avoiding Heap copies and lifetime dangling.
What you'll learn in this lesson
- Understand why
const std::string&can still cause hidden Heap allocations when passing"..."literals. - Replace read-only string parameters with
std::string_view(C++17) to get views and substrings inO(1). - Unify functions on C arrays,
std::arrayandstd::vectorviastd::span<const T>(C++20) by eliminating(const T* ptr, size_t len)pairs.
Overview
Suppose you have void log(const std::string& msg) and call it this: log("Request timeout"). That literal "..." is a const char*: to create the temporary std::string required by the parameter, C++ often has to allocate memory on Heap and copy all the bytes! The views (string_view, span) eliminate that cost.
A std::string_view takes up only 16 bytes (a const char* and a std::size_t length), passes by value, accepts both "letterali" and std::string without any allocation, and cuts substrings (.substr(), .remove_prefix()) into O(1)!
Sections covered in this lesson
- 11.
std::string_view(C++17): Pointer + Length - 22.
std::span<T>(C++20): The View for Buffers and Contiguous Vectors - 33. Comparison of Read-Only Signatures
- 44. When NOT to use
string_view(Beware of Lifetime!) - 5Practical exercises
- 6Check for understanding
Unlock "Zero-Copy Views: std::string_view and std::span" and the full Course C++ curriculum
Pass non-proprietary views on contiguous strings and buffers avoiding Heap copies and lifetime dangling.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course C++ plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.