Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector pointer and push_back()

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?

like image 302
el_pup_le Avatar asked Dec 17 '22 16:12

el_pup_le


1 Answers

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.

like image 196
GManNickG Avatar answered Jan 01 '23 17:01

GManNickG