So the answer depends on what version of c++ you're using
C++98
Because C++98 doesn't have std::begin
or std::end
the best move is just to accept you're going to have to pay the costs of construction and use std::string
. If you have boost available you should still consider boost::string_ref
for two reasons. First its construction will always avoid allocation, and is overall much simpler than std::string
.
boost::string_ref
works because it only stores a pointer to the string and the length. Thus the overhead is minimal in all cases.
c++11
Very similar to C++98 except the recommendation to use boost::string_ref
becomes MUCH stronger because c++11 has constexpr
which allows the compiler to bypass construction completely by constructing the object at compile time.
c++1z
Allegedly (it's not final) the Library Fundamentals TS will be bringing us std::string_view
. boost::string_ref
was a prototype for an earlier proposal of std::string_view
and is designed to bring the functionality to all versions of C++ in some form.
On C++14 String Literals
C++14 introduced string literals with the syntax "foo"s
unfortunately this is just a convenience. Because operator""s
is not constexpr
it cannot be evaluated at compile time and thus does not avoid the penalty that construction brings. So it can be used to make code nicer looking, but it doesn't provide any other benefit in this case.