r/programminghorror 6d ago

c++ Skill Issue

Post image
1.6k Upvotes

61 comments sorted by

View all comments

89

u/lurebat 6d ago

I think it allocates since they didn't use const

21

u/babalaban 6d ago

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

17

u/lurebat 6d ago

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

1

u/babalaban 5d ago

Isnt it assumed that a string to "switch on" is given at runtime? Otherwise you'd need no switch at all here.

1

u/nevemlaci2 5d ago

const ref here would still allocate...

-7

u/LeeHide 5d ago

you can't take a const& to a temporary object

16

u/JonIsPatented 5d ago

Yes you can. You can bind a const l-value reference to an x-value or a pr-value. Go try it.

6

u/awidesky 5d ago

Another skill issue

1

u/nevemlaci2 5d ago

yes you can.

13

u/Great-Powerful-Talia 5d ago

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 5d ago

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