3

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

Baum mit Augen
  • 47,658
  • 24
  • 139
  • 177
truf
  • 2,504
  • 22
  • 39

1 Answers1

13

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
  • 47,658
  • 24
  • 139
  • 177
  • 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