C++ / CHAPTER 03

Owned strings and borrowed string views

Advanced

Keep the owner alive for every use of a text view.

By the end of this chapter

  • Distinguish string ownership from a view
  • Track view length separately from termination
  • Avoid dangling references after mutation

The idea

std::string owns its character storage, while std::string_view describes a sequence owned elsewhere. A view is cheap to copy, but copying it does not extend the owner’s lifetime. Use an owning string when the result must survive its source. These examples use C++17 or later and deliberately keep the owner unchanged while its views are used.

A view has an explicit length and need not end at a null terminator. Passing view.data() to an API that expects a terminated string can therefore expose characters beyond the view. Mutations that reallocate the owner can invalidate views just as they invalidate pointers. At an API boundary, document whether text is borrowed for the call or retained, and copy into owned storage before retaining it.

C++ example
#include <iostream>
#include <string>
#include <string_view>
int main() {
  std::string owner = "bluebird";
  std::string_view view(owner.data(), 4);
  std::cout << view << ' ' << view.size() << '\n';
}
Result
blue 4

The view selects four characters while owner retains their storage.

Try it yourself

Write a helper returning an owned prefix when the result must outlive its input.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

A function constructs a local std::string and returns a string_view into it. What is wrong?