by tines · 7y ago · 0 comments
Constant folding via constexpr in C++ is much much better than C.
Templates help write generic code that results in specialized machine code; it may be hyper optimized at the cost of binary size. They make it harder to write code that at runtime is a little more type generic (if that makes sense). You can't always afford those additional copies generated. Not that it's a bad thing; just an observation as I write both strictly C and C++ at my day job.
Stealing the below; string handling is significantly safer with std::string. I'm not sold on std::string_view.
It's not pretty, but it's not hard either, and gives you full control over how many instances there are around. When C++ is used in a heavily constrained environment, that can come in handy.
That being said, string_view is arguably safer than passing around a char* and a length.
Literally had to write a psuedo borrow checker to stop it: https://youtu.be/80BZxujhY38?t=1095
So much work rather than admit the interface is bad and you should feel bad.
C++: "shoot yourself in the ~~foot~~ face."
I'm not entirely sold on string_view or span yet. But I wasn't sold on tuples either and I use them a lot now.
That being said, yes, string semantics are hard. Passing around copies of a string buffer (std::string) or calling to_string_view everywhere don't seem better.
These alone are a worthwhile "dialect" on top of C, the use of which results in a far safer C; and—as far as I know—these smart-pointer types and their compile-time semantics would be impossible to implement without C++'s additional layered-on "C with classes" type system.
(It's clear that these smart-pointer types are a valuable addition to C, because they were independently implemented as part of all sorts of other C macro libraries in the early 90s. I think there were at least four C smart-pointer implementations that existed as part of various parts of Windows, for example.)
Manually referencing and de-referencing exactly when needed avoids most of this. Sometimes it's perfectly safe to pass the same reference through several layers without changing the number of references.
As an added bonus YOU get do decide which references, if any, need to support multiple threads.
How is this helping us go anywhere worth going?
I was talking about std::shared_ptr, which is the closest thing to reference counting that STL offers.
Still, it's just too many layers of complexity for my taste. Nailing performance problems in C is a Sunday walk in the park in comparison.
Live and let live, I was just sharing my experience of going back and forth.
Imagine if C had a solid AST-based macros system...
Because of operator overloading, I don't know if `A * B` is incurring a (nontrivial, arbitrary) function call. Maybe it's just normal scalar multiplication, maybe it's finding the dot product of two arbitrarily sized matrices.