TT_ stands with Russia
TT_ stands with Russia

Reputation: 1912

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?

Upvotes: 0

Views: 87

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308111

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...

Upvotes: 2

James Curran
James Curran

Reputation: 103485

  • 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.

Upvotes: 1

Related Questions