Reputation: 3111
I wonder if there is a way to programmatically disable string SSO to make it not use local buffer for short strings?
Upvotes: 5
Views: 2404
Reputation: 3078
With GCC at compile time you can use the older Copy-On-Write std::string
implementation over the newer Small String Optimisation (SSO) by adding the following to your CMake file:
add_compile_definitions(_GLIBCXX_USE_CXX11_ABI=0)
On a 32 bits architecture such as the Raspberry Pi Pico std::string
weights 24 bytes with SSO and only 4 bytes with COW.
Upvotes: 1
Reputation: 50101
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)
Upvotes: 16