C++17: std::string_view

std::string_view it’s class which can view std::string or const char* without ownership and without additional memory requesting.

SSO (Small string optimization)

std::string has optimization for small strings ( compiler specific feature, for gcc, clang and msvc there are different values ).

For example for GCC 7.3 this value is 16 bytes. If string has <=16 bytes it will be saved in stack inside std::string object. If more then 16 bytes, then data used for saving string will be in heap. Which means additional memory allocations.

It can be checked by overloading operator new in global space.

For example we have function:

In this example we will have constructed std::string object with additinal memory allocations. new() operation is high costed because it will call kernel method to get new space.

std::string_view allows to avoid additinal allocations.


It will be worse case if inside method will be called substr() method.

We will have two memory allocations , first time create std::string object, second time substr() allocate memory for substring.

std::string_view has almost all methods the same as std::string except modifing methods.

So with std::string_view substr() method we will also avoid additinal memory allocations.

Related standard document: p0254r2


Leave a Reply

Your email address will not be published.