Use the case of a modifiable string literal

Over the years this has been deprecated:

char *p = "abc";

Then made illegal in C ++ 11. However, many do not know that this is legal:

char *p = (char*)"abc";

Trap:

[C ++ 11, diff.lex] Programs that have a legitimate reason to process string literals as pointers to potentially modifiable memory are probably rare.

Is there a legitimate reason? Please focus your answer on hosted environments.

+4
source share
5 answers

, , , a la strtok("step-one|step-two|step-three|step-four", "|"), , strtok(NULL, "|") .

, - strtok("step-one|step-two|step-three|step-four", "|") - , strtok(NULL, "|") NULL, strtok .

strtok(str, delim) / - ++ Standard - .

, , , , " ", .

0

, , char * , . const char * ( ).

, (char *) a (const char *) ( , , , / ).

, a const char * , char (.. ), , ... , , (, ).

/, . , "const pointer" , " " .

+3

. :

const int x = 3;
int *ptr = (int *) &x;
+1

( V++ 6, ) , , , , , ( , C, ).

+1

, ( , ), C, char, const .

const_cast, , workaroud litteral char * const char *, , , . , , , .

, , K & R C (const ) , , .

My opinion is that this was acceptable several years or decades ago, when many third-party codes were not used constin the signature, and the constant repetition const_castwas really boring, but I now agree with the quote: I can’t imagine a legitimate reason to write at present char * p = "abc";, and not (gardens retro retro)char * p = (char *) "abc";

+1
source

Source: https://habr.com/ru/post/1611541/


All Articles