简体   繁体   English

从变量中删除const-ness

[英]Remove const-ness from a variable

i'm trying to remove const-ness from a variable (char*), but for some reason when i try to change the value, the original value of the const variable still remains the same. 我试图从变量(char *)中删除const-ness,但由于某种原因,当我尝试更改值时,const变量的原始值仍然保持不变。

 const char* str1 = "david";
 char* str2 = const_cast<char *> (str1);
 str2 = "tna";

now the value of str2 changes but the original value of str1 remains the same, i've looked it up on Google but couldn't find a clear answer. 现在str2的值发生了变化,但是str1的原始值保持不变,我在谷歌上查了一下,却找不到明确的答案。

when using const_cast and changing the value, should the original of the const variable change as well ? 当使用const_cast并更改值时,const变量的原始值是否也会发生变化?

The type of str1 is const char* . str1的类型是const char* It is the char that is const , not the pointer. 这是charconst ,而不是指针。 That is, it's a pointer to const char . 也就是说,它是一个指向const char的指针。 That means you can't do this: 这意味着你不能这样做:

str1[0] = 't';

That would change the value of one of the const char s. 这将改变其中一个const char的值。

Now, what you're doing when you do str2 = "tna"; 现在,当你做str2 = "tna";时你正在做什么str2 = "tna"; is changing the value of the pointer. 正在改变指针的值。 That's fine. 没关系。 You're just changing str2 to point at a different string literal. 你只是将str2改为指向不同的字符串文字。 Now str1 and str2 are pointing to different strings. 现在str1str2指向不同的字符串。

With your non- const pointer str2 , you could do str2[0] = 't'; 有了您的非const指针str2 ,你可以str2[0] = 't'; - however, you'd have undefined behaviour. - 但是,你有未定义的行为。 You can't modify something that was originally declared const . 您无法修改最初声明为const In particular, string literals are stored in read only memory and attempting to modify them will bring you terrible misfortune. 特别是,字符串文字存储在只读存储器中,试图修改它们会给你带来可怕的不幸。

If you want to take a string literal and modify it safely, initialise an array with it: 如果要获取字符串文字并安全地修改它,请使用它初始化数组

char str1[] = "david";

This will copy the characters from the string literal over to the char array. 这会将字符串文字中的字符复制到char数组。 Then you can modify them to your liking. 然后你可以根据自己的喜好修改它们。

str2 is simply a pointer. str2只是一个指针。 And your code just changes the value of the pointer, the address, not the string to which it points. 而你的代码只是更改指针的值,地址,而不是它指向的字符串。

What's more, what you are attempting to do leads to undefined behaviour , and will most likely result in runtime errors. 更重要的是,您尝试执行的操作会导致未定义的行为 ,并且很可能会导致运行时错误。 All modern compilers will store your string "david" in read-only memory. 所有现代编译器都会将您的字符串"david"存储在只读内存中。 Attempts to modify that memory will lead to memory protection errors. 尝试修改该内存将导致内存保护错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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