logoalt Hacker News

William_BB • today at 4:01 PM • 2 replies • view on HN

I'm not sure what's so "spooky" about this example. It's really obvious if you know what `std::string_view` is. `Sanitize()` signature is fishy to begin with -- it takes a single string by const ref, but returns a string view. And I don't even consider myself very experienced in C++.

Sure, it'd be nice if the compiler didn't allow you to write this code. But there are worse examples than this out there.


Replies

grg0 • today at 6:49 PM

I don't think that is a fair assessment. Imagine Sanitize() and its caller are defined in different files, which is a more realistic scenario. On the one hand, you look at Sanitize's signature and it is "fine" (I agree a string_view argument would be better); it is implicitly stating that the caller is responsible for the lifetime of the argument. Separately, you look at the call and it has a good chance of passing inadvertently. Marking std::string's constructor explicit would have been a slight improvement but it still doesn't solve the problem. Overall, the fact that this code is possible and yields different results under different optimization levels is just cooked. As a programmer, I want to focus on solving problems, not on keeping my guard up at 110% and working around bad language design choices.

To reply to GP: many projects specifically avoid the STL.

simonask • today at 6:32 PM

You have to know a lot about C++ to tell at a glance what's wrong with this code. I fall in that category, and I can tell you I think that the signature of Sanitize() looks extremely reasonable!

What's completely unreasonable here is how easy it is for code that looks reasonable in C++ to be deeply dangerous. This is a perfectly normal piece of code, and it looks like the author is even conscientious about nice things like avoiding too many string copies. We shouldn't be out here defending the absolutely unhinged semantics that led to this.

C++ is so extremely hostile that people who try to write good code end up with a very defensive style of programming if they know what they're doing. In my experience, this tends to either almost fully eradicate any performance benefits they were chasing by choosing C++ in the first place, or blow up the time it takes to deliver the product.