By know you’ve learned that references are pretty neat. But before references existed, there were pointers. Just like references, they are used to store a memory address. But while references are hard to use wrong, pointers allow you to abuse them in every possible way. They’re the bondage lovers of programming!
For instance: a reference has to have a valid address when you create it. And once created, the address can never change. You can’t create an empty reference and pass the address later on. Pointers on the other hand, can point to anything or nothing. And you can change the contained address as many times as you like.
In most circumstances, using a reference is a lot safer. When a function asks for reference arguments, you can just provide regular objects. It’s hard to do something wrong there. But you might run into problems when you want to return a reference. Take this code for example:
class players {
Memc<Player> list;
Player & add(Vec2 & pos, Str & name) {
5 Player & p = list.add();
p.set(pos, name);
return p;
}
10 Player & findByName(Str & name) {
FREPA(list) {
if(Equal(list[i].getName(), name) {
return list[i];
}
15 }
}
}
// global object
players Players;
20
// somewhere in your application
Players.add(Vec2(1,1), ”niceGuy”);
player & friend = Players.findByName(”coolGuy”);
The add() method won’t give you problems. The reference arguments will always exist when you pass the to this method. (Either they are real objects, or they are existing references. And references cannot be empty.) The result will be valid too, because we are certain a new object will be made and returned.
Now take a look at the method findByName(). This method also returns a reference to a player. As long as the player you’re looking for actually exists, there isn’t any problem. But what if it doesn’t? From what object would you return a reference? Remember, a reference can never be referencing a non existing object. So here are your options:
None of the options you have is a good idea. What we need is a way to have our method tell us “’Hey, I don’t have the object you’re looking for. Stop buggering me!”. Or something slightly more polite.