Vector pointer and push_back()

el_pup_le picture el_pup_le · Mar 18, 2011 · Viewed 21.6k times · Source

If I have

void f(vector<object> *vo) {

}

And I pass the address of a vector to f

vector<object> vo;
f(&vo);

How would I use push_back() to add to the vector?

Answer

GManNickG picture GManNickG · Mar 18, 2011

Dereference the pointer:

(*vo).push_back(object());
vo->push_back(object()); // short-hand

Note this is a basic concept of the language, you may benefit from reading a good book.


Note this has a glaring shortcoming:

f(0); // oops, dereferenced null; undefined behavior (crash)

To make your function safe, you need to correctly handle all valid pointer values (yes, null is a valid value). Either add a check of some kind:

if (!vo) return;
// or:
if (!vo) throw std::invalid_argument("cannot be null, plz");

Or make your function inherently correct by using a reference:

void f(vector<object>& vo) // *must* reference a valid object, null is no option
{
    vo.push_back(object()); // no need to dereference, no pointers; a reference
}

Now the onus is on the caller of the function to provide you with a valid reference.