Constant Pointers vs. References in C++

Started by
2 comments, last by Geou 16 years, 2 months ago
Here's what I know of pointers and references. They are both used to access another variable or object (well, pointers only point to the memory address of it but they can be dereferenced to access it). But constant pointers can't change what variable/object they point to. And so, are they any different than references? And if they aren't, is there any point to use them over references?
Advertisement
References are basically pointers which will always point to the same object, that is, once they are created they can never be re-assigned to another object. They also do not allow for pointer arithmetic directly, though you can coax a pointer from a reference.

Const-ness applies to references in the same way that it applies to pointers. The const keyword is always a good idea wherever it applies, for example, if you have a function taking a reference or pointer, and that object is not to be modified by the function, const is appropriate.


References are generally preferable to pointers, since they are safer. You should generally default to references unless they do not satisfy the requirements. Examples of when to use pointers are when you need to apply pointer arithmetic or you are interfacing with an external API which uses pointers.

throw table_exception("(? ???)? ? ???");

Constant can mean two things when it comes to pointers though.
The pointer itself (the variable containing an address) can be constant (p4,p5 below), or the data to which it points to can be constant (p2,p3 below).

char data;//some datachar* p1 = &data; //regular pointer to regular dataconst char* p2 = &data;//regular pointer to some constant datachar const* p3 = &data;//same as p2char *const p4 = &data;//constant pointer to regular dataconst char *const p5 = &data;//constant pointer to constant data


p4 is comparable to a reference, and p5 is comparable to a constant reference.
Thank you both for the clarification. I was mainly wondering about Hodgman's p4 (constant pointer) and p5 (constant pointer to a constant) in comparison to references, and my questions have been sufficiently answered.

This topic is closed to new replies.

Advertisement