by pavlov · 9y ago · 0 comments
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.
Either crash when messaging nil, or don’t crash when improperly messaging an object.
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.
Just one example: Java's type erasure trick does not work anymore when value types are type parameters, so it affects the build process. The current approach seems to be to construct specific instances at run time (or rather at class loader time). That is very late though, because some information (like return types) are lost after compilation.
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.
You put a bunch of stuff in a book and people are going to copy the stuff from the book into their programs. Bits of front-matter don't matter. Consider the GoF book and the havoc that mindless repetition of design patterns creates.
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...
I consider this to be important to code maintainability at least as much as to performance.
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.).
From the standard:
> A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]
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.
There is no guarantee that the pointers are valid, even if not null.
So besides checking for null, to be correct we need to call OS APIs to check for pointer integrity as well.
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.
So it's really important to be able to tell which ones they are!
> what do you get from checking for a condition that shouldn't happen? At most an assert is justified!
An assert is a check, still takes up a lot of reading time if you have to do it for every parameter on every function.
> You don't check for the infinitely many other conditions that shouldn't happen, either.
I check for all the things that the code allows to happen, because sooner or later they will happen. You have to do this if your code ever accepts user input; any input that is possible will, sooner or later, find its way in. So if something shouldn't happen the best course is to make it impossible in the code.
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.
Sadly I’ve never had the opportunity to use Erlang for work, I’d certainly like to give it a try. I suppose I should try it (or elixir) on a side project sometime since it’s always a bad idea to go blind.
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.
I'm working on quite big finite element desktop applications, where alone the reading of the data can take up quite a bit of time. The user can then apply all kinds of different operations on this data and if one of these operations fails because of a null pointer - then sure, the code is wrong - but nevertheless the user doesn't want to loose all of his previous work and wants to be able to save the changed data.
Sure there're cases that a failed operation might have corrupted the data, but you just can't tell this in every case, and often the data is still valid and only the operation couldn't be applied.
If I've learned something over the years, then that there's not one solution that works for all cases.
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).
>C is about machine representation, and it's typed just enough to map to hardware (specify ABI of functions).
I don't understand that at all. How do enums map to hardware? How do structs? Clearly the line is arbitrary. Would adding generics mean that C maps less to hardware? What would that even mean?
And if C is all about talking directly to the hardware, how come the language has no first class support for SIMD, for preload, for the various CPU flags? And to get back to our point, how does NULL map to hardware? A CPU has no issue addressing at 0, it's nothing special. An assembler doesn't treat address 0 differently from any other, unlike C explicitly does.
Join my religion and preach: C is not a macro assembler, C is not a macro assembler.
>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).
[citation needed]
>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).
My point is that in this case the rem pointer is an algebraic data type. Passing NULL here doesn't mean "please store rem at (void*)0" it means "I don't want rem". Except this is not expressed in C's type system so you don't know that unless you read nanosleep's implementation or its documentation. the rem pointer, unlike the req pointer, is nullable, therefore it's effectively an option type but as far as C is concerned they're the same type.
If you assert() it then you can catch the problem early on at a runtime cost (and only when the situation eventually arises). If you make this part of the type system the compiler can validate that statically at compile time.
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
If the empty state thing was in reference to smart pointers, it'd be a remarkable misunderstanding of how they work and how they should be used.
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.