I am developing a game using C++. I’ve read in a lot of places that using pointers in C++ should basically be avoided at all costs. I am still learning C++ and slightly confused by this.
I would like a player object that is persistent and lives for the duration of the game session. This object will contain the players inventory, player stats etc etc.
The player’s inventory is basically just a vector containing item objects (an ‘Item’ class I’ve created).
If someone can clarify the following it would clear up my confusion:
- When people say ‘pointers are bad’ do they mean standard C++ pointers? Are smart pointers deemed ‘ok’?
- How else could I access persistant objects allocated on the heap other than a pointer?
- If I want a method that finds an item in the players inventory, but returns NULL if the item is not found, how else can that be implemented without pointers? Since the item returned from ‘findItem’ should be editable (to change the items count for instance), at the moment I return a pointer to the item in the vector. Is this a valid use of pointers?
Any help would be much appreciated!
Yes, raw, C-style pointers are considered bad. Smart pointers are OK. There are situations where you need to use (smart) pointers – collections of polymorphic objects for example:
std::vector<std::unique_ptr<IObject> >.A persistent object doesn’t have to be on the heap. It can be an object with static storage duration or even an automatic object that lives just long enough – i.e. you create it in
main().Numerous ways – you can throw an exception (probably too harsh) or go the
stdway an return an iterator – similar to.end().