- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 395字
- 2021-06-10 18:27:58
Constant Pointers
Pointers can be declared as const which, depending on where you apply it, means that the memory the pointer points to is read-only through the pointer, or the value of the pointer is read-only:
char c[] { "hello" }; // c can be used as a pointer
*c = 'H'; // OK, can write thru the pointer
const char *ptc {c}; // pointer to constant
cout << ptc << endl; // OK, can read the memory pointed to
*ptc = 'Y'; // cannot write to the memory
char *const cp {c}; // constant pointer
*cp = 'y'; // can write thru the pointer
cp++; // cannot point to anything else
Here, ptc is a pointer to constant char, that is, although you can change what ptc points to, and you can read what it points to, you cannot use it to change the memory. On the other hand, cp is a constant pointer, which means you can both read and write the memory which the pointer points to, but you cannot change where it points to. It is typical to pass the const char* pointers to functions because the functions do not know where the string has been allocated or the size of the buffer (the caller may pass a literal which cannot be changed). Note that there is no const* operator so char const* is treated as const char*, a pointer to a constant buffer.
You can make a pointer constant, change it, or remove it using casts. The following does some fairly pointless changing around of the const keyword to prove the point:
char c[] { "hello" };
char *const cp1 { c }; // cannot point to any other memory
*cp1 = 'H'; // can change the memory
const char *ptc = const_cast<const char*>(cp1);
ptc++; // change where the pointer points to
char *const cp2 = const_cast<char *const>(ptc);
*cp2 = 'a'; // now points to Hallo
The pointers cp1 and cp2 can be used to change the memory they point to, but once assigned neither can point to other memory. The first const_cast casts away the const-ness to a pointer that can be changed to point to other memory, but cannot be used to alter that memory, ptc. The second const_cast casts away the const-ness of ptc so that the memory can be changed through the pointer, cp2.