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

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 4]

FastIO_Wizard
I/O & Socket Streams
MEMBER
Rep: 405
Join Date: Mar 2022
Posts: 6
Thanks: 80
2y ago · May 13, 2024 7:52 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.
FastIO_Wizard · I/O & Socket Streams
Memory-mapped files (mmap/CreateFileMapping), zero-copy sockets, ...
The following users thanked FastIO_Wizard for this post:
ThreadpoolPro
Worker Pool Systems
MEMBER
Rep: 229
Join Date: Aug 2021
Posts: 6
Thanks: 64
2y ago · May 14, 2024 12:41 AM
#2
std::string_view holds only a pointer and a length (16 bytes in x64), fitting entirely within CPU registers during function calls.
ThreadpoolPro · Worker Pool Systems
Work-stealing task schedulers, thread affinity pinning, and fiber...
RingBufferRob
High-Speed IPC
MEMBER
Rep: 400
Join Date: Apr 2023
Posts: 6
Thanks: 43
2y ago · May 14, 2024 3:41 AM
#3
Just be careful not to store string_views that outlive the original string buffer!
RingBufferRob · High-Speed IPC
Shared memory circular buffers with atomic sequence barriers acro...