Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pass by reference vs. pointer in a Class [closed]

Tags:

c++

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?

like image 829
Jean Finley Avatar asked Apr 19 '26 20:04

Jean Finley


2 Answers

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.

  • passing by pointer more accurately reflects how you're using the argument (although I can't tell whether that's useful semantic info or an implementation detail)
    • a call site passing a pointer (or the result of new directly) will look natural
    • a call site doing something stupid like passing the address of an automatic variable will stand out
  • passing by reference suggests the argument should not be NULL, which may or may not be correct and useful
like image 185
Useless Avatar answered Apr 21 '26 09:04

Useless


Whichever, 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.

like image 24
hcarver Avatar answered Apr 21 '26 09:04

hcarver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!