Mixing pointers and references in function definition in C++ [closed]

青春壹個敷衍的年華 提交于 2019-12-23 06:56:59

问题


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.



来源:https://stackoverflow.com/questions/31807775/mixing-pointers-and-references-in-function-definition-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!