Are there benefits of passing by pointer over passing by reference in C++?(在 C++ 中通过指针传递比通过引用传递有好处吗?)
问题描述
在C++中指针传递比引用传递有什么好处?
What are the benefits of passing by pointer over passing by reference in C++?
最近,我看到了许多选择通过指针传递函数参数而不是通过引用传递的示例.这样做有什么好处吗?
Lately, I have seen a number of examples that chose passing function arguments by pointers instead of passing by reference. Are there benefits to doing this?
示例:
func(SPRITE *x);
调用
func(&mySprite);
对比
func(SPRITE &x);
调用
func(mySprite);
推荐答案
指针可以接收NULL参数,引用参数不能.如果您有可能希望传递无对象",请使用指针而不是引用.
A pointer can receive a NULL parameter, a reference parameter can not. If there's ever a chance that you could want to pass "no object", then use a pointer instead of a reference.
此外,通过指针传递允许您在调用站点明确查看对象是通过值传递还是通过引用传递:
Also, passing by pointer allows you to explicitly see at the call site whether the object is passed by value or by reference:
// Is mySprite passed by value or by reference? You can't tell
// without looking at the definition of func()
func(mySprite);
// func2 passes "by pointer" - no need to look up function definition
func2(&mySprite);
这篇关于在 C++ 中通过指针传递比通过引用传递有好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中通过指针传递比通过引用传递有好处吗
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
