繁体   English   中英

为什么在何处以及为什么使用“指向常量的指针”,“常量指针”和“指向常量的常量指针”?

[英]Where and why do we use “pointers that point to constants”, “constant pointers”, and “constant pointers that point to constants”?

所以如果我在C ++中有这样的东西:

char A_char = 'A';
char * myPtr = &A_char;

const char * myPtr = &char_A; //pointers that point to constants
char * const myPtr = &char_A; //constant pointers
const char * const myPtr = &char_A; //constant pointers that point to constants

我想知道在编程中我们在何处以及为什么使用“指向常量的指针”,“常量指针”和“指向常量的常量指针”。 我知道它们及其语法之间的区别,但是我不知道我们在哪里以及为什么使用它们。 你能解释一下吗? 多谢你们。

常量指针是无法更改其持有的地址的指针。

<type of pointer> * const <name of pointer>

不能更改其指向的变量值的指针称为常量指针。

const <type of pointer>* <name of pointer>

指向常量的常量指针既不能更改其指向的地址,也不能更改保存在该地址的值。

const <type of pointer>* const <name of pointer>

您可以在此处找到有关其用法的更多详细信息: http : //www.codeguru.com/cpp/cpp/cpp_mfc/general/article.php/c6967/Constant-Pointers-and-Pointers-to-Constants.htm

如果数据不应更改:
使用指向常量数据的指针。
const char * myPtr = &char_A;

如果数据可以更改,但指向的内存不应该:
使用常量指针:
char * const myPtr = &char_A;

如果数据不应更改,并且指向的内存也不应更改:
使用常量指针指向常量数据:
const char * const myPtr = &char_A;

确实没有什么比这更多的了。

由于您要询问使用示例:

  • 指向常量char的指针的典型用法是将指针传递给只读存储器(例如,字符串文字)。 该内存可以取消引用但不能修改(未定义的行为)

     const char* myPtr = "this is read only memory"; 
  • 指向char的常量指针可能用于传递可以修改的缓冲区位置,但是不能更改该位置(即,您需要专门使用该内存区域)

     char * const myPtr = some_buffer_location; printBuffer(myPtr); void copyToBuffer(char * const &pointer_to_buffer /* Reference to pointer */) { const char* my_contents = "this is my content"; strcpy(pointer_to_buffer, my_contents); // Buffer contents can be changed // pointer_to_buffer = NULL; - error! Not assignable } 
  • 上面的组合可用于绕过只读存储区,并确保所指向的地址保持不变, 并且其内容保持不变。

要实现完全的const正确性是非常困难的 ,但是如果希望实现这一目标,则必须适当组合上述标志。

暂无
暂无

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

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