C++

Lesson 04

Const references and string_view

Use const references or string_view for read-only inputs so call sites avoid copies and mutation stays visible.

Good Code

src/review_title.cpp
#include <string_view>

bool has_review_prefix(std::string_view title, std::string_view prefix)
{
    // string_view borrows read-only text without copying it.
    return title.starts_with(prefix);
}

Bad Code

review_title.cpp
#include <string>

bool has_review_prefix(std::string title, std::string prefix)
{
    // Copying both strings hides the read-only intent.
    title.shrink_to_fit();
    return title.rfind(prefix, 0) == 0;
}

Review Notes

What to review

Good Code

The good version uses std::string_view for borrowed text. The signature communicates that the function reads the strings and does not retain them.

Bad Code

The bad version copies both strings, then mutates a copy inside a predicate. That makes a read-only check look heavier and less direct than it is.

Takeaways

  • Read-only C++ parameters should say whether they borrow data, copy data, or mutate data.