Hacker News new | ask | show | jobs
by abbeyj 1286 days ago
I think that would be safer. But then it would presumably disallow things like:

    void frob(std::string_view sv);
    std::string a = "a";
    std::string b = "b";
    frob(a + b);
This is allowed today and does not have any problems that I'm aware of. You could work around this by changing the call to:

    frob(std::string_view(a + b));
But that feels cumbersome. I think the goal of std::string_view was to be useful as a parameter for a function so that you could pass in anything remotely string-like and it would implicitly convert and do what you meant. Requiring explicit conversions at the call sites would go against that goal.

Another thing that was desired was the ability to take an existing function that takes a `const std::string&` and change it to instead take a `std::string_view` and not have to update any of the callers. If some callers that worked with the old function are going to need an update to work with the new function then it gets a lot harder to change the function. Or maybe impossible if you don't control all of the callers.

I don't see how you can get both the ease-of-use and the safety short of reinventing something like Rust's lifetimes.

1 comments

I certainly don’t disagree with you there (about ease-of-use vs safety). I personally believe the “right” choice in C++ is to err on the side of safety (at least when adding new stuff), and wish STL did too — especially given how notoriously difficult it is to write C++ code that isn’t plagued with memory corruption bugs

I know anything other than switching to Rust is a losing battle of compromises in some sense, but many of us working with huge codebases written in C++ don’t have the luxury of that choice being unavailable.

If you write C++ code plagued of memory bugs maybe it is bc you take it too far. I fo not think it is particularly hard to write memory safe code.

Sure you mist avoid a few things but there are alternatives on what to do instead/not what to do.

Ok, so downvote and no reply:

- you can use string_view more conservatively

- you can stick to value semantics.

- use spans in things that do not escape.

- use smart pointers.

- do not capture escaping lambdas that have capture by reference.

If you go wild raw pointers willy-nilly around, then yes, you are gonna have a plague of sh*t because you are an incompetent using C++. I do not expect people to play the violin or drive a car without a minimal of training.

I'm guessing that the downvotes were because people were focusing on how easy c++ makes it to unwittingly introduce such bugs.

So suggesting a disciplined usage of c++ sounded like a hard sell. It's helpful that you elaborated on the details.

It is not so much of a disciplined thing compared to what you need to do in C...