I'm currently trying to learn C++. In learning, I like to try weird things to get a grasp of the language and how memory works. Right now, I'm trying to create a class who has an array of characters that is set on construction. The only method of my class is to be able to get the array via a pointer on an argument. I've successfully created my class and it works just fine, but now I want to make it more secure by making sure that I never change the value of the array.
This is what I have so far:
#import <stdio.h>
class MyClass {
public:
char const * myArray;
MyClass(char inputChar[]){
myArray = inputChar;
}
void get(const char * retVal[]){
*retVal = myArray;
}
};
int main(){
char myString[] = {'H','E','L','L','O'};
MyClass somethingNew = MyClass(myString);
const char * other = new char[4];
somethingNew.get(&other);
std::cout << other[0];
return 0;
}
I noticed that I cannot change the value of the array at all by using the dereference operator:
myArray[0] = 'h';
And this is good, but that doesn't mean that I cannot change the pointer of where myArray[0] points to:
*(&myArray) = new char('h');
Is there any way to prevent against this?
--- Resolution ---
#import <stdio.h>
typedef const char * const constptr;
class MyClass {
public:
constptr * myArray;
MyClass(constptr inputChar) {
myArray = &inputChar;
}
void get(constptr * retVal){
retVal = myArray;
}
};
int main(){
char myString[] = "Hello";
MyClass somethingNew(myString);
constptr other = new char[4];
somethingNew.get(&other);
std::cout << other[0];
return 0;
}
This means that I cannot do any of the following:
*myArray[0] = 'h';
*myArray = new char[4];
*&*myArray = new char('h');
But I can do this:
myArray = &inputChar;
Yes, you have to create a const pointer to a const object like this:
char const * const myArray;
The first const
as you know, keeps you from modifying what the pointer points to; the second const
keeps you from re-assigning something else to the pointer.
You might also consider using a const reference, which is pretty much the same.
EDIT:
As Benjamin Lindley points out, since the pointer is now constant, you need to assing a value to it in the intialization list, not the constructor body, like this:
MyClass(char inputChar[])
: myArray(inputChar) {
}
You need to create a const
pointer like so:
char const * const myArray;
That is a const pointer to a const char.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.