C ++对象:我应该何时使用指针或引用 [英] C++ Objects: When should I use pointer or reference
问题描述
我可以使用一个对象作为它的指针,或者它的引用。我理解,区别是指针必须手动删除,引用仍然保留,直到它们超出范围。
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:
- Pointer vs. Reference
- C++ difference between reference, objects and pointers
推荐答案
引用基本上是一个带有限制的指针(必须在创建时绑定,不能被反弹/ null)。如果你的代码使用这些限制是有意义的,那么使用引用而不是指针允许编译器警告你不小心违反了它们。
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 ++对象:我应该何时使用指针或引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!