[英]Example of const pointer to a constant value
我知道在 c++ 中我们可以有一个指向常量值的常量指针:
const int value{ 5 };
const int* const ptr{ &value };
这表示:
ptr
持有的memory地址不能更改。ptr
使用间接来改变value
这样的指针什么时候有用?
例如,当使用指针迭代时,您可以在数组结束后存储 position。 这对于避免在比下面的更复杂的循环中意外修改指针很有用。 如果除此之外您不希望数组是可修改的,您还将使元素类型为 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;
}
}
并非所有数据都需要在每种情况下都进行更改。 例如,您可能想要编写一个 function 对大量数据进行一些聚合分析。 您不需要修改它来计算有关它的东西,因此在这种情况下,将这种指针作为参数传递是有意义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.