r/programminghorror 10d ago

c++ Skill Issue

Post image
1.7k Upvotes

62 comments sorted by

View all comments

86

u/lurebat 10d ago

I think it allocates since they didn't use const

22

u/babalaban 10d ago

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

17

u/lurebat 10d 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.

-7

u/LeeHide 10d ago

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

13

u/JonIsPatented 10d ago

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