int& toref(int* ptr) {
return *ptr;
}
//snip
int& i = toref(0);
i = 5; // segfault
One thing I kind of appreciate at times about C++ (or at least about certain implementations) is the fact you can call methods on null pointers and you can check in the method if it's called on a null pointer. I.e.
class A {
public:
int foo() {
return this == null ? 1 : 2;
}
};
//....
A* a = 0;
std::cout << a->foo();
Which allows you to make classes that work just fine even if you use a null pointer.
Yes, it's theoretically possible. The point is, you need to explicitly do evil things to get "null references". The language cannot and is not meant to protect you from yourself.
> One thing I kind of appreciate at times about C++ (or at least about certain implementations)
Yes, certain implementations indeed. It is formally undefined behavior, so anything at all could happen if you do that; the most straightforward and efficient implementation just happens to "work".
> The point is, you need to explicitly do evil things to get "null references". The language cannot and is not meant to protect you from yourself.
No, you don't need to do evil things at all. Any C api that returns a pointer which you then need to pass to a C++ function that takes a reference is a possible source of failure if you forget to check your pointer. It can happen quite easily by mistake. The language cannot in any way guarantee that you won't make a reference from a null pointer. At least taking a reference as an argument does at least alert people that you're not expecting to be passed a null as an argument to your function.
A fair point. Still, only having to check for nulls on certain API boundaries is much less work than the alternative, and it's easy to train oneself to automatically spot "dangerous" points where a pointer-to-reference conversion is done.
Well, ironically, C++ already has non-nullable pointers. They're called references and they work extremely well.