简体   繁体   中英

How to make a function not to use the STL container parameter (similarly to null pointers)?

I'm sure it was already answered here, but can't find it... Say, a function has a parameter which is a reference to an STL vector. Sometimes the function has to fill out the vector, sometimes it does not. How can I let the function know when it should not fill out the vector? If the parameter was a pointer, then calling the function with null/not-null pointer would do the job. Is it possible to do the same with references without using pointers or additional parameters?

Added: What If I use the following function call:

func( std::vector<int>() );

And function header is:

func( std::vector<int>() &vec )
{...}

When how is it going to work? I've seen this trick in the real code. Does it mean the function still performs an action on the vector, but the caller should not bother about creating a vector in his code?

This doesn't necessarily qualify as a best practice, but it can be done. Ordinarily an optional parameter is specified with a pointer instead of a reference. But you can create a sentinel object that has special meaning to your function.

static std::vector<MyStuff> MyVecNull;

void MyFunc(std::vector<MyStuff>& vec = MyVecNull)
{
    if (&vec != &MyVecNull)  // only do the following if a vector was passed...
  • You could use two different functions.
  • Personally, I prefer using references as a light-weight way to pass a large read-only object, and pointers if I'm going to change the object. That way the call has the & right on it to show that we're going to change that object.

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