C++ 我们在哪里以及为什么使用;指向常量的指针"&引用;常量指针“;,及;指向常量的常量指针“;?

C++ 我们在哪里以及为什么使用;指向常量的指针"&引用;常量指针“;,及;指向常量的常量指针“;?,c++,pointers,constants,C++,Pointers,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 t

所以如果我在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

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

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

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


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


其实没有什么比这更重要的了。

常量指针是一个无法更改其所持有地址的指针

<type of pointer> * const <name of pointer>
*常数
一个不能改变它所指向的变量值的指针称为常数指针

const <type of pointer>* <name of pointer>
const*
指向常量的常量指针是既不能更改其指向的地址,也不能更改保留在该地址的值的指针

const <type of pointer>* const <name of pointer>
const*const
您可以在此处找到有关其用法的更多详细信息:

既然您要求使用示例:

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

  • 指向char的常量指针可用于传递可以修改的缓冲区位置,但该位置不能更改(即,您需要专门使用该内存区域)

  • 上述组合可用于传递只读存储器区域,并确保指向的地址保持不变,其内容保持不变


实现完全常量正确性是极其困难的,但如果想要实现这一目标,则必须将上述标志适当组合。

可能的重复非常相似,但一个是“它们是什么?”另一个是“我们什么时候使用它们?”
常量T*
是最有用和最常见的。它只允许函数读取数据。通过严格控制程序的哪些部分可以修改数据,可以更容易地设计程序和调试。可能的重复
const char* myPtr = "this is read only memory";
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
}