Mixing pointers and references in function definit

2019-06-15 00:52发布

问题:

I have a function that has two instances of classes as arguments:

void cookPasta(const Tomato& tomato, const Meat* meat)
{
    if (meat != nullptr)
        cookPastaWithMeat(tomato, *meat);
    else
        cookPastaWithoutMeat(tomato);
}

As the function shows, an instance of Tomato is always required, whereas Meat is optional and a nullptr can be passed instead. I do this to allow the cookPasta function to be called even if the user has never declared an instance of the Meat class.

Is it bad practice to mix references and pointers in the function signature?

回答1:

The one thing you lose with this approach is the possibility to pass in a temporary Meat, as its address can't be taken.

Why not use overloading, by simply renaming cookPastaWithMeat and cookPastaWithoutMeat ?

void cookPasta(const Tomato& tomato, const Meat& meat);
void cookPasta(const Tomato& tomato);


回答2:

Your Practice is good

  • You've used const keyword.
  • Passing reference
  • But, 2nd parameter pointer can be little better using optional parameter feature of C++. check out here.

    void cookPasta(const Tomato& tomato, Meat* meat = nullptr)
    {
        if (meat != nullptr)
            cookPastaWithMeat(tomato, *meat);
        else
            cookPastaWithoutMeat(tomato);
    }
    


Now, Call the same function in both way.

cookPasta(tomato); // meat will default to nullptr
cookPasta(tomato, meat);


回答3:

It's good practice since you have a good reason for doing so: a pointer can be nullptr whereas a reference must always be passed. You are exploiting this elegantly.

Using const means that the function cannot modify the parameters passed from the caller; that's good too.