205 points · by mindB · 9y ago · 151 comments
This submission is likely the result of the recent livestreams that myself and Araq have been making. You can check out my past livestreams[1] and Araq's[2] at the links below. If you're into watching us live the next time we create a livestream then follow d0m96 (https://go.twitch.tv/d0m96) and araq4k (https://go.twitch.tv/araq4k) on Twitch.
1 - https://www.youtube.com/watch?v=UQ4RvUlXIDI&index=3&list=PLm...
2 - https://www.youtube.com/watch?v=E2qlDKm_WzE, https://www.youtube.com/watch?v=UV38gQfcb9c
Don't forget about embedded systems: they could be the killer platform which makes Nim mainstream overnight.
I won't forget about embedded systems, but I'm not sure this platform has that much power to change things overnight
Also, when you’re thinking in pointers, it’s easy to add levels of indirection with the same mental tools (pointers to pointers, etc.) Personally I find it’s easier to solve problems with a limited orthogonal toolset than a sprawling array of marginally differently balanced optimizations, which is what most of C++ has become.
Rust, Swift, Guava, etc. all get this right. Option types need to become a language feature for all statically-typed languages. C++ should adopt it too.
They aren't zero-cost abstractions in most languages. Every unwrap() potentially results in a dynamic check, even if one isn't necessary. There are a number of ways you could extend a type system to track the potential cases of sum types, which would help alleviate this cost.
Ask me about using a Java library that could return an option type, which could be null, so you have to check for both the None return value AS WELL AS null.
No, you don't -- because those are two different kinds of null!
If your library's function returns Optional.empty(), then it's because it successfully returned no value. If it returns null, though, then the library has a bug and you should crash instead of trying to continue in a known invalid state.
Without the Optional type signature, the function would return null for both of these, and your program will appear to work even though it's just suffered a bug.
I'm not sure I agree with that. See how MS did that in C# 7:
https://www.kenneth-truyers.net/2016/01/25/new-features-in-c...
https://wiki.openjdk.java.net/display/valhalla/Minimal+Value...
Until then it is an issue that we have to live with.
They apparently got the memo: http://en.cppreference.com/w/cpp/utility/optional
Another thing you won't find in this book is the C++ Gospel, the One True Path to perfect C++ software. Each of the Items in this book provides guidance on how to develop better designs, how to avoid common problems, or how to achieve greater efficiency, but none of the Items is universally applicable. ...
If you follow all the guidelines all the time, you are unlikely to fall into the most common traps surrounding C++, but guidelines, by their nature, have exceptions. That's why each Item has an explanation. The explanations are the most important part of the book.
Scott Meyers - Effective C++
The problem is not "Effective X" books. The problems is people treating these rules in these books as dogma.
Rant: Personally since working on my game engine in C, my architecture has become so much simpler, I can easily avoid unnecessecary allocations. My code is much more coherent. Aspect-oriented - which is not at all OO spirit, since OO encourages (trying) to bundle things in self-contained packages.
Yes, that seems hard to believe, since there is so much bad C code out there. With allocations, strings, file system operations etc. all over the place, just as in typical OO code. (Of course some things are really hard to do in C vs C++. The point is forcing myself to have a good architecture and avoid having to make many meaningless decisions).
[1] https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80...
Let it go. Let it crash. Just assume inputs are non-null (except where null makes sense). Even C crashes safely on null pointer dereference.
There are several solutions in C++.
1. Always check for null. Kind of annoying and lots of people don't for whatever reason.
2. Use references. As you say, annoying because then you can't have null (sensibly) even when it would be really useful.
3. Use std::optional<int&> or something like that. I only just thought of this and don't know if it would work, but I bet it's a pain.
So no great solution. Personally I would use a smart pointer type, document it as well as I can, and always check for null.
As I pointed out I usually don't have null pointers at all. There might be a few places where a value can very obviously be null, but they are far and far between. No need for documentation.
> Boom segfault.
Which is exactly the right thing to happen (it's the C version of Exceptions in dynamic languages) since the code was incorrect.
> Always check for null. Kind of annoying and lots of people don't for whatever reason.
And now what do you do if you detected null but it was not allowed? Throw an exception? You can have that for free by just not checking.
> Use references. As you say, annoying because then you can't have null (sensibly) even when it would be really useful.
C++ references don't really protect you from NULL. It's just a different syntax for the same thing.
> Use std::optional<int&> or something like that. I only just thought of this and don't know if it would work, but I bet it's a pain.
Yes, pain, big pain. So much line noise and typing (in both senses) around what is essentially an int.
Just don't check. I don't get why there's so many places for null pointers. (As I said elsewhere, I don't have a solution for JSON style microscopic programming, and I don't care about that.).
use assert or some custom always-assert-even-on-release macro.
> Use references. As you say, annoying because then you can't have null (sensibly) even when it would be really useful.
well, only use references for non nullable pointers. Otherwise use plain (or smart) pointers.
> Use std::optional<int&> or something like that. I only just thought of this and don't know if it would work, but I bet it's a pain.
std::optional<T&> is unfortunately not part of C++17, mostly because people couldn't agree on operator= semantics:
int x = 1; int y = 2; std::optional<int&> oint = x;
oint = y; // which one is true? assert(x == y); // deep assign assert(&*oint == &y); // rebind
boost::optional supports references and IIRC rebinds on plain assignment.
The trouble is it's not always clear whether null is a meaningful value or not. The type of an expression should tell you what values it might take - that's the whole point of a type. Having the same type for pointers that could be null and pointers that will never be null is like having the same type for integers and floating-point numbers.
> Even C crashes safely on null pointer dereference.
False. A null pointer dereference in C is undefined behaviour and can therefore easily be a security flaw (there's been at least one local root vulnerability in Linux due to this).
> False. A null pointer dereference in C is undefined behaviour and can therefore easily be a security flaw (there's been at least one local root vulnerability in Linux due to this).
Yes. in theory... and yes I heard there are also some stupid compiler optimizations around this. Still, the point is, what do you get from checking for a condition that shouldn't happen? At most an assert is justified!
You don't check for the infinitely many other conditions that shouldn't happen, either.
That's just asking for a disaster. Null pointer dereferences are undefined behavior in C, and compilers can and do make these assumptions, leading to all kinds of horrors. (https://software.intel.com/en-us/blogs/2015/04/20/null-point...)
"Maybe something" is not rare. In fact it's often just as common as "Definitely something" in my experience. A customer maybe has a shipping address. You could bend over backwards and say that either he has an address or else the address reference must point to the special no-address value instad of being null.
But in that scenario you still need to check for whether it's the no-address or an actual adreess. Otherwise you might end up doing things like trying to set the street address of the no-address value which could either throw an exception or (worse) suddenly everyone without address lives at that address.
So the only real solution is to use proper types to model "maybe something". You can use a list of addresses for the customer. That naturally supports 0..N. Or you could use a proper option type (which is just a collection with max count 1).
On the other hand, you can reap huge benefits from data-oriented programming (basically, make a separate email table that has a "foreign key" to the customer table) to do processing in the large. This is where C is a very good fit and you have no null pointers :-)
It must be nice to work in an environment where nobody cares about results.
Not crashing when there's a bug is not "success", it's just "zero visible errors"!
If your workplace really cares about results, they'll understand how futile it is to keep executing even though there's a bug. You start second-guessing your own program, which makes the code quality worse as the assumptions it makes are no longer clear; you won't be alerted to problems, as the program won't be aware of any; there'll be no guarantee that your code isn't just working "by accident" at the moment.
I'd love it if the code I deal with just crashed instead of pretending everything's alright, because it makes errors far harder to diagnose.
Does it? What if you needed to clean up external resources? What if some data was left in an inconsistent state? What if you were in the middle of writing to a file? Etc.
I do agree that crashing is often the right thing to do and of course the machine can die anyway, but sometimes you want to at least attempt to recover.
Also, in much of the software I've written in recent years, crashing was not acceptable because just because one thing (eg request of some kind, message, task, whatever) failed unexpectedly, does not mean that others will too and we still want others to be attempted. Sometimes you can get away with letting the program crash and then restarting it to run the other work, but often things are done concurrently and restarting would lose any in-progress state. If the work takes a long time, restarting all work because one piece failed is often unacceptable.
Maybe have a look at Erlang? I suppose it's more aligned with what you want to do. There you also "crash", but only managed, green, processes with very convenient communication channels.
If the amount of work done before the crash has some value and is lost by the crash, then crashing just isn't an option.
Uh, that's a rather optimistic way to look at this. In C NULL pointer dereference is UB so you shouldn't rely on this behaviour. For one thing the compiler is allowed to do weird things if it can statically assert that a NULL reference takes place, for instance by dropping any code that can be proved to lead to a NULL dereference. Not so safe or friendly.
Most of the time for userland apps dereferencing a NULL pointer for reading or writing will cause a segfault but that might not be the case for bare metal/MMU-less applications. Furthermore even when it does crash it simply terminates the process without any unwinding which might leave non-volatile data in a non-consistent state.
The real problem with pointers is that they're effectively an algebraic data type, they can point to something or be NULL. But the type system can't enforce that, there's no concept of non-nullable pointers in C.
Take the prototype of nanosleep(2) for instance:
int nanosleep(const struct timespec *req, struct timespec *rem);
Turns out that the 2nd parameter is NULLable if you don't care for the reminder. The first one isn't however, so passing NULL there is a big no-no.In rust the equivalent signature would be something like:
fn nanosleep(req: TimeSpec, rem: Option<&mut TimeSpec>) -> Result<(), i32>;
Which is a lot more explicit (mind you, that's probably not what the API of nanosleep would look like in rust since output parameters are not very common, you'd probably return rem in the Result).The problem is the same on the library side. When you're passed a pointer, should you assume it's nullable? Should you check for it? If you want to be safe you do, and you end up with a bunch of redundant checks.
It's also easy to end up with a NULL-ish pointer that's not NULL if you happen to offset a NULL pointer by mistake (like a NULL array or NULL struct pointer). That can be pretty tricky to track down since the crash doesn't occur when the offset is calculated but rather when the bogus quasi-NULL pointer is dereferenced:
#include <stdio.h>
struct s {
int a;
int b;
};
void bar(int *i) {
if (i == NULL) {
printf("NULL\n");
} else {
printf("%d\n", *i); /* i is invalid but not NULL, this (probably) crashes */
}
}
void foo(struct s *ps) {
int *b = &ps->b; /* ps assumed not-NULL here */
bar(b);
}
int main(void) {
foo(NULL); /* This is where the actual error takes place,
foo's argument is not NULLable */
return 0;
}
Also consider what happens if we're using a NULL pointer to a very large buffer. Dereferencing the beginning of the buffer would probably crash but higher addresses might end up in mapped pages and you start accessing and possibly overwriting random parts of the runtime.> The real problem with pointers is that they're effectively an algebraic data type
No, they are not. Join my religion and preach: pointers are just data, pointers are just data. And be free.
C is about machine representation, and it's typed just enough to map to hardware (specify ABI of functions). Don't be deluded to think you can represent all (or even many) invariants in types. Some other languages try to do that (and it always ends up in a big mess).
If you want more "safety" - which (for the things you still need to implement) just means crash in a more friendly way, not less - then use a managed language. But they come with their own pros and cons, of course.
To address the issue with nanosleep, this is not what we were talking about. nanosleep does expect a null pointer in the second argument. (And I think in this rare case an assert(req) would be justified. Or maybe just split it into 2 functions).
Talk to me about how good an idea it is not to check potentially-NULL pointers in embedded systems.
Obviously references are better in most circumstances but only because you don't have to check for an empty or invalid state. They offer no performance or optimization on their own.
I always assumed that a default-constructed unique_ptr<T> was simply a NULL pointer under the hood. So you have exactly the same representations of "nothing" as you do with a T
Foo foo; foo.init_from_file("/tml/lol"); if (foo) { // do some stuff }
we could be getting Foo objects by value from a factory, which constructs and moves the Foo objects. References are meant for situations where the object CANNOT be null/invalid by contract, so you are missing the point amigo.
You say operator bool() is the one true way. Many other people define "empty" states for their objects that sometimes make sense only to the library author. Others use class wrappers. Someone else came up with a cool trick for a Maybe-style functor, I'm sure. Yet another bright person has built his very own mind-bending approach using move semantics and some odd corner of the C++14 spec.
With C++, you never know what to expect until you dig into the API. It's an impediment to doing anything with the language unless you work on a huge project where coding standards are rigid and external dependencies come in every once a century (which many C++ projects are, certainly).
The massive incidental complexity in C++ made it almost impossible to write a working compiler. For example, it remains extremely difficult to write a parser for the C++ language. The syntax also has horrible aspects like List<Set<int>> being interpreted as logical shift right. None of the original C++ compilers were reliable. Only after two decades did we start to see solid C++ compilers (by which time C++ was in decline in industry due to Java and C#).
C++ is said to be fast but the reality is that C++ is essentially only fast when you write C-like code and even then it is only fast for certain kinds of programs. Due to the "you don't pay for what you don't use" attitude, C++ is generally inefficient. RAII injects lots of unnecessary function calls at the end of scope, sometimes even expensive virtual calls. These calls often require data that would otherwise be dead so the data are kept alive, increasing register pressure and spilling and decreasing performance. The C++ exception mechanism is very inefficient (~6x slower than OCaml) because it unwinds the stack frame by frame calling destructors rather than long jumping. Allocation with new and delete is slow compared to a modern garbage collector so people are encouraged to use STL collections but these pre-allocate huge blocks of memory in comparison so you've lost the memory-efficiency of C and then you are advised to write your own STL allocator which is no better than using C in the first place. One of the main long-standing advantages of C over modern languages is the unpredictable latency incurred by garbage collectors. C++ offers the worst of both worlds by not having a garbage collector (making it impossible to leverage useful concepts like purely functional data structures properly) but it encourages all destructors to avalanche so you get unbounded pause times (worse than any production GC). Although templates are abused for metaprogramming they are very poor at it and C++ has no real support for metaprogramming. For example, you cannot write an efficient portable regular expression library in C++ because there is no way to do run-time code generation and compilation as you can in Java, C# and languages dating back to Lisp (1960). So while Java and C# have had regular expressions in their standard libraries for well over 10 years, C++ only just got them and they are slow.
C++ is so complicated that even world experts make rookie mistakes with it. Herb Sutter works for Microsoft and sits on the C++ standards committee where he influences the future of C++. In a lecture he gave his favorite 10-line C++ program, a thread-safe object cache.
My personal feeling is that the new Rust programming language is what C++ should have been. It has useful known features like generics, discriminated unions and pattern matching and useful new features like memory safety without garbage collection.
If you've ever used unstable software that crashes in a dozen different ways you can thank null pointers.
Modern C++ isn't about substituting references for pointers, it is about dealing with values and removing a level of indirection that pointers gives.
The old style of of using pointers everywhere frequently usually implies a lot of small heap allocations which is also a big performance problem. Both these things end up being huge detriments to speed and stability.
If you've objects with an invalid state then you've nothing won compared to a null pointer.
But the point is to make invalid state not representable as much as possible, then the reasoning of code gets a lot easier, because the invalid state can't distribute throughtout the application.
I do agree that people are a little too fearful of using bare pointers for optional references, if you're using a linter that will catch possible null dereferences it's often the most sensible technique.
Even if it only showed a date, and no time, the time zone is relevant. The Internet is supposed to be for the whole world, not just one time zone.
That's OK, it's better to get it right, and it's still useful for small projects in the meantime. But Nim seems like a language that is never truly finished.
I like this direction. I tried to avoid "ref" in my last Nim project, but it's too hard to do that for every type the way the language is currently designed.
True for every language.
"1.0" will freeze the spec and it's not like the current versions are unstable or unusable.
- `type Foo = object` --> Value type, on the stack
- `type Foo = ref object` --> Reference type, managed by GC
- `type Foo = ptr object` --> Pointer type, manual memory management (with Nim's equivalent for malloc, free and memcopy)
Also Nim does not have 1 GC but several:
- Default Deferred Reference Counting - Not stop the world
- Boehm GC
- Mark and Sweep
- Memory Regions
- Real-time GC (with tunable max-pause)
- GC disabled
GC can also be deactivated per thread (setupForeignThreadGc) or for a section of the code (GC_ref, GC_unref) even on Ref types to improve interoperability with other languages.
(Look at Donald Knuth's TeX for an example of this style.)
However all Pascal dialects had extensions for low level pointer manipulation.
But you can't do pointer arithmetics in Nim.
Either
- `type Foo = object` -> Value type, on the stack
- `type Foo = ref object` -> Ref type, managed by GC
- `type Foo = ptr object` -> Pointer type, manual memory management (malloc, free, memcopy ...)
[1] shameles plug: https://github.com/duneroadrunner/SaferCPlusPlus
The C/C++ code generated by the Nim compiler is then free to use unsafe constructs including the dreaded goto.
The fact the author had so many problems with GC bugs is somewhat reassuring. Would be interesting to see a GC-less Nim in a production use-case.