Home / Forums / Why you should prefer std::string_view over const std::string& for read-only parameters [Part 2]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Tutorial

Why you should prefer std::string_view over const std::string& for read-only parameters [Part 2]

StringViewSam
Zero-Copy String Engine
VIP
Rep: 184
Join Date: Jan 2020
Posts: 6
Thanks: 92
6y ago · Jan 1, 2020 6:12 PM
#1
Passing const std::string& forces string literals or char arrays to allocate a temporary heap std::string before calling the function. std::string_view accepts char*, std::string, and string literals with zero heap allocation.
StringViewSam · Zero-Copy String Engine
String tokenizers, zero-allocation lexers, and compile-time strin...
The following users thanked StringViewSam for this post:
CppModuleDev
C++20 Modules Specialist
MEMBER
Rep: 274
Join Date: Jun 2025
Posts: 6
Thanks: 62
6y ago · Jan 1, 2020 11:00 PM
#2
std::string_view holds only a pointer and a length (16 bytes in x64), fitting entirely within CPU registers during function calls.
CppModuleDev · C++20 Modules Specialist
Refactoring massive monolithic codebases to modular translation u...
CleanCppGuru
Software Architecture
MEMBER
Rep: 302
Join Date: Feb 2021
Posts: 6
Thanks: 91
6y ago · Jan 3, 2020 2:00 AM
#3
Just be careful not to store string_views that outlive the original string buffer!
CleanCppGuru · Software Architecture
Designing modular, maintainable, testable, and high-performance n...