Different between C++ pointers and references?

匿名网友 匿名网友 发布于: 2015-08-30 00:00:00
阅读 118 收藏 0 点赞 0 评论 0

Because a reference must refer to an object, C++ requires that references be initialized.
Notice that there is no such thing as a null reference.

Another important difference between pointers and references is that pointers may be reassigned to refer to different objects. A reference, however, always refers to the object with which it is initialized

In general, you should use a pointer whenever you need to take into account the possibility that there’s nothing to refer to (in which case you can set the pointer to null) or whenever you need to be able to refer to different things at different times (in which case you can change where the pointer points). You should use a reference whenever you know there will always be an object to refer to and you also know that once you’re referring to that object, you’ll never want to refer to anything else

Other occassions: you’ll almost always want operator[] to return a reference.

评论列表
文章目录