简体   繁体   中英

Behaviour about const_cast<>

I have written a small problem for checking the behavior of const_cast on const data member.

using namespace std;


     class myString{
         public:
                 myString(char * str)
                 {
                         p=str;
                 }
                 const char * getString(){
                         return p;
                 }
         private:
                 const char *p;
 } ;


int main()
{
        char *p=(char*)malloc(8);
        cin>>p;
        myString *m= new myString(p);
        char *s =const_cast<char*>(m->getString());
        s[6]='y';
        cout<<s<<endl;
        return 0;
}

After running this program I give the out as "yogendra" (a 8 letter string). and i got the output as "yogendya" Now my doubt. Through const_cast<> we can override the behavior of the data member itself as here the string is const char* still after casting i can modify it.

You've described exactly what const_cast is for - it allows you to removed the const ness from something and modify it. It's up to you not to abuse that power. :-)

(In your case this doesn't apply, but note that you can cause crashes by using const_cast - for example:

const char *c = "Hello";
char *s = const_cast<char*>(c);
s[0] = 'h';

could crash because the compiler can put the string literal into read-only memory.)

yes, you can use const_cast<> this way and it will not be an undefined behaviour since object pointed to by const char* in your class is indeed non-const of type char* . but be careful:. C++ standard. §7.1.​5.1/4 says

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior

safe use of const_cast is to ie cast const from const reference to a non-const object: when there is non const object and you have const ref to it, you can cast const from this safely

If you say

char *s =const_cast<char*>(m->getString());

then you essentially remove the "const" from the pointer, and you declare your s to be a pointer to char, and it's a writable string. So the next line

s[6]='y';

is perfectly fine. To keep the const you ought to declare s as a const pointer

const char *s = m->getString();

in which case you won't be able to overwrite the constant string (error: assignment of read-only location). I assume that is what you want? The const_cast will simply add/remove the const and in your case, remove it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM