Is the code below safe? It might be tempting to write code akin to this:
#include
Whether or not two string literals with the exact same content are the exact same object, is unspecified, and in my opinion best not relied upon. To quote the standard:
[lex.string]
16 Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified.
If you wish to avoid the overhead of std::string
, you can write a simple view type (or use std::string_view
in C++17) that is a reference type over a string literal. Use it to do intelligent comparisons instead of relying upon literal identity.