指向常量值的 const 指针示例

cha*_*ham 1 c++ pointers

我知道在 C++ 中,我们可以有一个指向常量值的常量指针:

const int value{ 5 };
const int* const ptr{ &value };
Run Code Online (Sandbox Code Playgroud)

这意味着:

  • 所持有的内存地址ptr无法更改。
  • 我们不能使用间接通过ptr来改变value

这样的指针什么时候有用?

fab*_*ian 6

例如,当使用指针进行迭代时,您可以在数组的末尾存储位置。这对于避免在比下面更复杂的循环中意外修改指针很有用。如果除此之外,您不希望数组可修改,您还将使元素类型为 const;这导致指向 const 元素的 const 指针很有用:

void printArray(int const* array, size_t count)
{
    int const* pos = array;
    int const* const end = array + count; // end is the pointer past the count-th element of array

    while(pos != end)
    {
        std::cout << *pos << std::endl;
        ++pos;
    }
}
Run Code Online (Sandbox Code Playgroud)