How to detect use of std::string short string optimization?
13:48 01 Nov 2025

If you have a long string:

std::string data("This is a string long enough so that it is not a short string");

Then you have a view onto that string:

std::string_view dataView(std::begin(data) + 5, std::end(data) - 5);

If I move the original string:

std::string movedData(std::move(data));

Then I would expect the view dataView to remain valid.

But, this assumption does not hold if the std::string short string optimization takes effect, as the underlying memory of the string is not dynamically allocated, and the move now (underneath the hood) becomes a destructive copy operation leaving the view invalid.

Questions:

  1. Is there something in the standard about this?

  2. Is there a way to detect short string optimization (so I can take appropriate action in my class move constructor)?

c++ string optimization string-view