null a vector of pointers in a parameter?

Started by
4 comments, last by Aardvajk 9 years, 1 month ago

Hi guys,

Just wondering if it's possible to nullptr or NULL the following function parameter...


void foo(std::vector<Entities*> &e){


}

For example, I am looking for something like this

void foo(nullptr) but it does not work with a container

Thanks,

Mike

Advertisement

A reference must refer to a valid object, but your null-pointer is not a valid vector object. If you want to pass an optional parameter, you can pass a pointer to the vector instead of a reference so you can pass a null-pointer to indicate the absence of a vector.

Do you absolutely need a null-able parameter? Or could it be an empty container? How would the behavior of the function differ?

If an empty container would work, you can now do this:

foo( {} );

Which will send an empty array down.

Thanks a lot for the help guys

Boost::optional might also be worth considering for this kind of case. Allows for no special state (empty container) meaning "not there".

Also consider that the functionality is kind of built into std::vector already (given a size() function), so passing in an empty temporary vector as suggested by Ameise is a pretty good idiom (no dynamic allocations happening there, fear not).

Since you pass a vector of Entity*, it is likely that the code you envision will look something like:


void foo(vector<Entity*> &e)
{
    if(e != null_vector_ref)
        for(auto elem& : e)
        {
            elem->blah();
            ...
        }
}

If there are simply no elements inside the vector, that loop will execute zero times, with or without an explict check. Since the branch for the explicit check is not free, this is most likely even more efficient. Or, you could just do if(!e.size()) if you definitively wish to be explicit, or if your function is a little more complicated and contains several loops.

This topic is closed to new replies.

Advertisement