c++中函数定义中指针和引用的混合
Mixing pointers and references in function definition in C++
我有一个函数,它有两个类实例作为参数:
void cookPasta(const Tomato& tomato, const Meat* meat)
{
if (meat != nullptr)
cookPastaWithMeat(tomato, *meat);
else
cookPastaWithoutMeat(tomato);
}
如函数所示,总是需要一个Tomato
的实例,而Meat
是可选的,可以传递一个nullptr
。我这样做是为了允许调用cookPasta
函数,即使用户从未声明过Meat
类的实例。
在函数签名中混合引用和指针是不好的做法吗?
这种方法失去的一件事是传入临时Meat
的可能性,因为它的地址不能被占用。
为什么不通过重命名cookPastaWithMeat
和cookPastaWithoutMeat
来使用重载呢?
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
意味着函数不能修改调用者传递的参数;
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- 混合 C 和 C++.. 对函数的未定义引用
- 混合转换指针和引用
- 结构化绑定和转发引用是否混合良好?
- 重值引用不是将类型和类别混合在一起吗?
- 模板功能:混合逐个复制传递和按引用传递
- 在OpenMPI中混合使用“英特尔C++”和“Fortran”时未定义的引用
- 混合按引用传递和按值传递到可变参数模板函数有效
- 如何混合C++共享指针和对象引用
- 期望输出带有指针和引用混合的代码
- 混合编译gfortran和g++时未定义的引用
- c++中函数定义中指针和引用的混合
- C++/Fortran 混合编程:对"_gfortran_reshape_r8"的未定义引用
- 运算符[]中混合引用和值行为
- Android NDK 混合 C 和 C++ 错误未定义对 mult(int, int) 的引用