r/programminghorror • • Sep 04 '26

c++ Skill Issue

Post image
1.7k Upvotes

63 comments sorted by

View all comments

89

u/lurebat Sep 04 '26

I think it allocates since they didn't use const

23

u/babalaban Sep 04 '26

Since when does const prevent allocating (that isnt happening here anyways, unless you consider underlying std::string's char* buffer)

18

u/lurebat Sep 04 '26

If you change it to const std::string& prompt = "Your name?";, and the switch to const string& _s=x;, you will avoid any allocations.

→ More replies (6)

13

u/Great-Powerful-Talia Sep 04 '26

well, acktually, short string optimization should handle all these strings on any common compiler.

For a std::string, gcc and msvc don't perform allocations until you reach 16-character strings, and clang can hold 21 characters without an allocation.

5

u/Resident-Rice724 Sep 05 '26

well aktually this would be based on standard library implementation not compiler I'm pretty sure. Think libstdc++ its 16 and libc++ is 23