Reputation: 1912
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
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
Reputation: 103485
&
right on it to show that we're going to change that object.Upvotes: 1