C++ Objects: When should I use pointer or reference(C++ 对象:什么时候应该使用指针或引用)
问题描述
我可以使用一个对象作为指向它的指针,或者它的引用.我知道不同之处在于必须手动删除指针,并且引用会一直保留到超出范围.
I can use an object as pointer to it, or its reference. I understand that the difference is that pointers have to be deleted manually, and references remain until they are out of scope.
我应该什么时候使用它们?有什么实际区别?
When should I use each of them? What is the practical difference?
这些问题都没有回答我的疑问:
Neither of these questions answered my doubts:
- 指针与参考
- C++ 引用、对象和指针的区别
推荐答案
引用基本上是一个有限制的指针(必须在创建时绑定,不能被反弹/为空).如果您的代码使用这些限制是有意义的,那么使用引用而不是指针可以让编译器警告您不小心违反了它们.
A reference is basically a pointer with restrictions (has to be bound on creation, can't be rebound/null). If it makes sense for your code to use these restrictions, then using a reference instead of a pointer allows the compiler to warn you about accidentally violating them.
它很像 const 限定符:没有它,语言也可以存在,它只是作为一种额外的功能,可以更容易地开发安全代码.
It's a lot like the const qualifier: the language could exist without it, it's just there as a bonus feature of sorts that makes it easier to develop safe code.
这篇关于C++ 对象:什么时候应该使用指针或引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 对象:什么时候应该使用指针或引用
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
