c++ - 指向常量值的 const 指针示例
问题描述
我知道在 c++ 中我们可以有一个指向常量值的常量指针:
const int value{ 5 };
const int* const ptr{ &value };
这表示:
- 所持有的内存地址
ptr
不能更改。 - 我们不能使用间接通过
ptr
来改变value
这样的指针什么时候有用?
解决方案
例如,您可以在使用指针迭代时存储数组结束后的位置。这对于避免在比下面的更复杂的循环中意外修改指针很有用。如果除此之外您不希望数组是可修改的,您还将使元素类型为 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;
}
}
推荐阅读
- postgresql - 如何从 PostgreSQL 的并发事务中从一个表的字段中获取最新的新 id
- javascript - 此代码在哪里返回鼠标位置值?
- flutter - LateInitializationError:使用easy_localization国际化flutter应用程序时,字段'_deviceLocale@66168148'尚未初始化
- javascript - MongooseServerSelectionError: 连接 ECONNREFUSED ::1:27017
- java - 在这个问题中如何避免嵌套的for循环
- java - 如何调用 OAuth 端点以获取在 java 中启用 x509 的 accesstoken?
- python - Python scipy 最小化 - 不产生预期回报的简单示例
- http - 这个访问令牌是如何存储在客户端的,在 FastAPI 的教程“Simple OAuth2 with Password and Bearer”中
- python - 在 Tkinter GUI 中创建内置命令行
- java - 使用 AssertJ 在单元测试中检查 Map 条目内的列表