logoalt Hacker News

moltopoco • yesterday at 10:12 PM • 2 replies • view on HN

Just one data point, because I have to get it off my heart. I loved Modern C++ when it meant C++11, but I've become more negative with each new language standard reaching my workplace.

Using string_view over string by default is probably the #1 cause of memory errors that landed on my desk. I also keep hearing that "int x{0}" is preferable to "int x = 0" which allows for super dangerous implicit conversions, but then the same people rewrite push_back into emplace_back, which is much more lenient w.r.t. type conversions. It is also much easier to litter every function with [[nodiscard]] constexpr nothrow than it is to argue for readability.

My best explanation is that "Modern C++" is making developers biased towards whatever language feature is newer, instead of making good decisions. I wish the community gave up on the moniker.


Replies

spacechild1 • yesterday at 11:10 PM

`string_view` (and `std::span`) is great! Finally I don't have to use concrete types like `const std::string&` or `const std::vector<float>&` as function parameters when all I really want is just something that behaves like a string or array/vector type.

In fact, `std::string_view` can lead to very elegant and efficient (zero-allocation) string parsing code.

IME, taking a string_view as an argument is pretty unproblematic. Two areas where I have seen problems:

1. returning a string_view from a function. Think twice before doing that.

2. calling data() and passing the result to a function that expects a null-terminated C strings. (std::string_view is not guaranteed to be null-terminated.)

---

Apart from that, there are so many great features and libraries in C++17 and C++20 that I use on a regular basis and that I would really miss:

- structured bindings

- if-statement initializers

- fold expressions

- inline variables (very useful for handling global state in header-only stuff)

- if constexpr (replaces many uses of SFINAE)

- concepts (replaces all of the remaining uses of SFINAE)

- coroutines (really nice to use with ASIO)

- std::optional

- std::variant

- std::filesystem

- std::format (although I personally stick to fmt::format)

- from_chars() and to_chars() (fast, local-independent string-number conversion routines)

- std::bit

- std::apply, std::invoke, std::bind_front

- etc.

William_BB • yesterday at 11:17 PM

To be fair, string_view has one very attractive feature over const ref string. String's char constructor is not explicit. With string view, you are guaranteed to not allocate by accident.