Six years ago I wrote on the WebKit blog about Using References Instead of Pointers. Re-reading that post today, I remember how excited I was about the technique back then.
In the years since that post, references have become part of my everyday C++ vernacular, and consequently references are widely used in Serenity. I’m writing this post to refresh myself on what’s great about references, and to share my views with you, dear reader. So let’s get to the reasons I love these things…
If you write a function that takes a Foo*, it may receive a Foo, but you may also receive nullptr. Since you don’t know this at compile-time, you have to somehow deal with the scenario in which someone passes you a nullptr.
If it’s an error to call the function with nullptr, a common technique to catch bad calls is to assert at runtime that the pointer is non-null:
While I’m definitely in favor of assertions, I do consider it a bug whenever I see a function that takes a pointer and immediately asserts that it’s non-null.