c++stringstdstring

Disable std:string's SSO


I wonder if there is a way to programmatically disable string SSO to make it not use local buffer for short strings?


Solution

  • As SSO is an optional optimization, there won't be a standard way to turn it off.

    In practice, you can just reserve a string that won't fit into the SSO buffer to force the buffer being allocated dynamically:

    std::string str;
    str.reserve(sizeof(str) + 1);
    

    That seems to work for gcc at least and should even work portably as the internal buffer needs to fit inside the string. (Live)