• Advertisement
Sign in to follow this  

null a vector of pointers in a parameter?

This topic is 1144 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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

foo( {} );

 

Which will send an empty array down.

Share this post


Link to post
Share on other sites
Boost::optional might also be worth considering for this kind of case. Allows for no special state (empty container) meaning "not there".

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement