C++ string_view in SaferCPlusPlus

C++ string_view in SaferCPlusPlus

C++ string_view in SaferCPlusPlus

std::string_view is, in a way, a problematic addition to the standard library in the sense that it has an intrinsically unsafe interface. That is, its constructors support only (unsafe) raw pointer iterator parameters. In contrast, the standard library generally uses iterator types which allow for the option of a memory-safe implementation. So to enable memory safe use, this library’s version, mstd::string_view, generalize the interface to support construction from safe iterator types. So while technically mstd::string_view can act as a drop-in replacement for std::string_view, it is designed to be used with safe iterator types, not unsafe raw pointer iterators.

Like std::string_view, mstd::string_view is defined as an alias for mstd::basic_string_view<char>. The mstd::wstring_view, mstd::u16string_view and mstd::u32string_view aliases are also present. Note that mstd::basic_string_view<> is in fact just a slightly augmented version of TAnyStringConstSection<>.


#include "msepoly.h" // mstd::string_view is defined in this header
#include "msemstdstring.h"
void main(int argc, char* argv[]) {
/* std::string_view stores an (unsafe) pointer iterator into its target
string. mse::mstd::string_view can instead store any type of string iterator
, including memory safe iterators. So for example, when assigned from an
mse::mstd::string, mse::mstd::string_view will hold one of mse::mstd::string
's safe (strong) iterators (obtained with a call to the string's cbegin()
member function). Consequently, the mse::mstd::string_view will be safe
against "use-after-free" bugs to which std::string_view is so prone. */
mse::mstd::string_view msv1;


mse::mstd::string mstring1("some text");
msv1 = mstring1;

/* This is not undefined (or unsafe) behavior. */
auto ch1 = msv1[3]; /* In debug mode this will fail an assert. In non-debug
mode it'll just work (safely). */
assert('e' == ch1);

catch (...)

/* At present, no exception will be thrown. Instead, the lifespan of the
string data is extended to match that of the mstd::string_view. It's
possible that in future library implementations, an exception may be thrown*/
mse::mstd::string mstring2("some other text");

/* With std::string_view, you specify a string subrange with a raw pointer
iterator and a length. With mse::mstd::string_view you are not restricted to
(unsafe) raw pointer iterators. You can use memory safe iterators like those
provided by mse::mstd::string. */

auto msv2 = mse::mstd::string_view(mstring2.cbegin()+5, 7);
assert(msv2 == "other t");