|
|
|
|
|
by anon4
4540 days ago
|
|
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".