c++中函数定义中指针和引用的混合

Mixing pointers and references in function definition in C++

本文关键字:引用 混合 指针 函数 定义 c++      更新时间:2023-10-16

我有一个函数,它有两个类实例作为参数:

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

如函数所示,总是需要一个Tomato的实例,而Meat是可选的,可以传递一个nullptr。我这样做是为了允许调用cookPasta函数,即使用户从未声明过Meat类的实例。

在函数签名中混合引用和指针是不好的做法吗?

这种方法失去的一件事是传入临时Meat的可能性,因为它的地址不能被占用。

为什么不通过重命名cookPastaWithMeatcookPastaWithoutMeat来使用重载呢?

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

你的做法很好

  • 您使用了const关键字。
  • 传递引用
  • 但是,第二个参数pointer可以使用c++的optional parameter feature稍微好一点。点击这里查看

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


现在,以两种方式调用同一个函数

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

这是一个很好的实践,因为您有一个很好的理由这样做:指针可以nullptr,而引用必须始终传递。你巧妙地利用了这一点。

使用const意味着函数不能修改调用者传递的参数;