So, I have a class which stores a vector of pointers to objects. I have a method that adds objects to the vector. When adding, I know I can pass by reference or by pointer, and have read about the advantages and disadvantages of each, but in this case, I can't figure out which one is better and why. For all I can figure out, they're pretty much the same (but I'm probably wrong!)
Here's (a paraphrasing of) passing by pointer/address:
hpp:
class Room {
vector<Item*> items;
public:
void addItem(Item*);
};
cpp:
void Room :: addItem(Item* item) {
items.push_back(item);
}
...and pass by reference:
hpp:
class Room {
vector<Item*> items;
public:
void addItem(Item &);
};
cpp:
void Room :: addItem(Item &item) {
items.push_back(&item);
}
Which should I use?
It doesn't matter in the slightest, so do whatever seems more natural at the call site, or is more consistent with the rest of the code.
OK, I can see points in favour of each, but I can't tell you if they matter in your case.
new directly) will look naturalNULL, which may or may not be correct and usefulWhichever, depending on the context of the rest of your programme.
Both will work fine, so it's more a question of which will make the code clearer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With