There are several libraries that allow you to do this. Such as boost::string_ref
and llvm::StringRef
. A similar class, string_view
(upon which boost::string_ref
is based), is in the works for future standardization. If you don't want to download another library, the class is fairly simple to implement. It is little more than a const char*
to indicate the start of the sub-string, and an integer to indicate the length (alternatively, another pointer to indicate the end point), plus some utility functions.
A common thing to be aware of with all these classes, is that you need to make sure that the source string remains alive and unmodified (or at least, ensure no reallocations happen) for as long as the referencing object is used. In other words, treat them with the same care as you would a pointer (since that's essentially what they are).