Remix.run Logo
BeetleB 5 days ago

> Here’s a rule of thumb I like to follow for C++: make it look as much like C as you possibly can, and avoid using too many advanced features of the language unless you really need to.

Also, avoid using C++ classes while you're at it.

I recently had to go back to writing C++ professionally after a many-year hiatus. We code in C++23, and I got a book to refresh me on the basics as well as all the new features.

And man, doing OO in C++ just plain sucks. Needing to know things like copy and swap, and the Rule of Three/Five/Zero. Unless you're doing trivial things with classes, you'll need to know these things. If you don't need to know those things, you might as well stick to structs.

Now I'll grant C++23 is much nicer than C++03 (just import std!) I was so happy to hear about optional, only to find out how fairly useless it is compared to pretty much every language that has implemented a "Maybe" type. Why add the feature if the compiler is not going to protect you from dereferencing without checking?

butterisgood 5 days ago | parent | next [-]

I really don't like Object Oriented programming anywhere. Maybe Smalltalk had it right, but I've not messed with Pharo or anything else enough to get a feel for it.

CLOS seems pretty good, but then again I'm a bit inexperienced. Bring back Dylan!

account42 4 days ago | parent | prev | next [-]

Using classes doesn't have to mean OO. Classes in C++ are important for RAII which you definitely should not avoid.

fluoridation 5 days ago | parent | prev [-]

std::optional does have dereference checking, but it's a run-time check: std::optional<T>::value(). Of course, you'll get an exception if the optional is empty, because there's nothing else for the callee to do.

BeetleB 4 days ago | parent | next [-]

> but it's a run-time check

And that's the problem. In other languages that have a Maybe type, it's a compile time check. If your code is not handling the "empty" case, it will simply fail to compile.

I honestly don't see any value in std::optional compared to the behavior pre-std::optional. What does it bring to the table for pointers, for example?

fluoridation 4 days ago | parent [-]

Nothing, but I don't think anyone uses std::optional<T *>. However, if you need to specify an optional integer, std::optional is much clearer than encoding the null value as a negative or other such hacks. Another use of std::optional is to delay construction of an object without an extra dynamic allocation. That's way more convenient than using placement new.

afdbcreid 4 days ago | parent | prev [-]

But the dereference operator invokes UB if there is no value.

Which is a recurring theme in C++: the default behavior is unsafe (in order to be faster), and there is a method to do the safe thing. Which is exactly the opposite of what it should be.

account42 4 days ago | parent [-]

No, it's the reason people choose C++.