Sign in to follow this  
Geou

Constant Pointers vs. References in C++

Recommended Posts

Geou    122
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?

Share this post


Link to post
Share on other sites
Ravyne    14300
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.

Share this post


Link to post
Share on other sites
Hodgman    51326
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 data

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



p4 is comparable to a reference, and p5 is comparable to a constant reference.

Share this post


Link to post
Share on other sites
Geou    122
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this