Skip to main content
Module 9 · Lesson 4 of 422/26 in the course~15 min
Module lessons (4/4)

Zero-Copy Views: std::string_view and std::span

Lesson preview5 hands-on exercises readyCourse C++ · Module 9 — Move Semantics, Lambda and STL Modern

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 in O(1).
  • Unify functions on C arrays, std::array and std::vector via std::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

  1. 11. std::string_view (C++17): Pointer + Length
  2. 22. std::span<T> (C++20): The View for Buffers and Contiguous Vectors
  3. 33. Comparison of Read-Only Signatures
  4. 44. When NOT to use string_view (Beware of Lifetime!)
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 9 — Move Semantics, Lambda and STL Modern

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.