Question
std::string_view vs std::string: Ownership vs Performance Trade‑off
Tasadduq BurneyownerOwner · Founder
25K reputation · 08 Oct 2023, 12:53 UTC
77.2K views0
Goal
Design a function that accepts textual data while balancing zero‑copy performance with lifetime safety. The decision centers on whether to expose std::string_view for read‑only consumption or require std::string to enforce ownership.
Constraints & Uncertainty
- Zero‑copy semantics of
std::string_viewavoid allocations but risk dangling references if the caller’s buffer is destroyed or mutated during the call. - Passing a literal or temporary to a
std::stringoverload triggers construction of a temporary, incurring an allocation or move, which can be costly in high‑throughput or embedded contexts. - The C++ standard provides neither a preferred overload nor a guideline, leaving library designers to choose arbitrarily.
Unresolved Decision
Should read‑only APIs default to std::string_view to eliminate unnecessary copies, or should they default to std::string to guarantee safety against dangling references?
Questions
- When is it acceptable to expose only
std::string_viewfor a function that never stores the incoming data? - What safety checks or documentation can mitigate the risk of dangling
std::string_viewreferences in public APIs? - In performance‑critical code paths, how can we quantify the trade‑off between the allocation cost of
std::stringand the potential risk of undefined behavior withstd::string_view?