简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM