std::string_view accepting temporaries: good idea or horrible pitfall?
C++17 brings us std::string_view
.
It is a really useful tool:
If you want to write a function accepting some string, but does not need ownership, i.e. a view,
use std::string_view
.
It supports both const char*
and std::string
without any work,
and does not involve any heap allocations.
Further, it clearly signals intent: this function takes a view.
It doesn’t own anything, it just views it.
As someone who frequently advocates for using correct types,
I am happy about std::string_view
.
Yet there is one design decisions that warrants a discussion:
std::string_view
silently views temporaries as well.
This can create a problem if the view lives longer than the temporary,
as the view now views already destroyed data.
Let’s look into the reasons behind this decision
and what that means for using std::string_view
.