I wonder if there is a way to programmatically disable string SSO to make it not use local buffer for short strings?
Asked
Active
Viewed 1,777 times
1 Answers
14
As SSO is an optional optimization, there won't be a standard way to turn it off.
In reality, 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)

Baum mit Augen
- 49,044
- 25
- 144
- 182
-
Any known downside of using this approach? – Sayantan Ghosh Jan 17 '21 at 12:52
-
1@SayantanGhosh The obvious one is that by disabling the optimization, you lose its performance benefits. The more interesting question here is: What would be the upside of doing this? If your code doesn't work with SSO, but does without, you'd be better off fixing your code than tinkering with the symptoms. – Baum mit Augen Jan 17 '21 at 23:25
-
I was facing this same issue with set emplace: https://stackoverflow.com/questions/56896539/stdvectorstdwstring-is-moving-reallocating-inner-wstring-data-legal Was evaluating manual allocation using a char array vs the above for this since the allocation brings in some set of additional management on free up. – Sayantan Ghosh Jan 18 '21 at 04:39
-
@BaummitAugen one example is storing string views (or raw pointers) into a string. Usually this is perfectly valid with move semantics, but when the string uses sso it'll fail. Quite annoying to be honest. – Bas Feb 26 '23 at 18:19