简体   繁体   English

编程实践char *指向const的指针或指向const的数组

[英]Programming practice char * pointer to const or array to const

I know that following is bad programming practice 我知道以下是不好的编程习惯

char * p1 = "myBad"  ;  

The above is bad as const "myBad" memory is getting pointed by non Const pointer . 由于const“ myBad”内存被非Const指针指向,因此上述情况很糟糕。 Compilers allow p1 as to support backward compatibility with C 编译器允许p1支持与C的向后兼容性

IS the following a bad practice too ? 以下做法也是不好的做法吗?

char p2[]="myBadORGood";

Whats the difference betweeen p1 and p2 . p1和p2之间有什么区别。 DOes compiler make a non-const copy for p2 ? 编译器会为p2创建非常量副本吗? I think i read somewhere that p2 is fine but not sure .. 我想我在某处读到p2很好,但不确定..

p2由字符串文字初始化,即它是字符串文字的副本 ,因此p2为非const可以:

char p2[]="myGood";

The first is not only bad practice but deprecated in C++ (C++03; according to chris' comment this is even illegal now in C++11 ). 第一个不仅是不好的做法,而且在C ++中也不推荐使用 (C ++ 03;根据chris的评论,这在C ++ 11中现在甚至是非法的 )。

The second is totally fine, the string literal is only used as a (read-only) "model" to initialize a new, independent array. 第二个完全没问题,字符串文字仅用作(只读)“模型”来初始化新的独立数组。 Thus, the short 因此,短

char arr[] = "abc";

is equivalent to the longer 相当于更长的时间

char arr[] = { 'a', 'b', 'c', '\0' };

and can even be written like this: 甚至可以这样写:

char arr[4];
arr[0] = 'a';
arr[1] = 'b';
arr[2] = 'c';
arr[3] = '\0';

(but don't write code like that! ^^) (但不要写这样的代码!^^)

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

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