c - Const robustness of pointer inside a struct and performance
问题描述
I have a struct like this
struct S {
int l;
double* very_large_data;
}
On this struct I want to act upon various functions. In particular there are some function for which I want an instance of S to be read only. However if I define
int read_only(const struct S* S_ptr) {
...
*very_large_data = ... // OK, no error
...
}
inside the function I can always access and modify the value of data pointed by very_large_data
. In order to prevent this one can of course modify the struct definition to
struct S {
int l;
const double* very_large_data;
}
in that way is not possible to to modify data even if the structure is passed as non const pointer
int write_on_S(struct S* S_ptr) {
...
*very_large_data = ... // ERROR, this is a pointer to const.
}
in this way one would be forced to reallocate the pointer to modify the data. This would require possibly very large operations with memory.
Which would be the best design to enforce "logical" const correctness without introducing some costly memory operations?
解决方案
你总是可以抛弃你的const
功能内部,即
int write_on_S(struct S* S_ptr) {
double *data = (double *)S->very_large_data;
*data = 42.0;
}
very_large_data
如果没有指向实际const
限定的对象,这是有效的。
推荐阅读
- sql-server - SQL Server 动态筛选器
- c# - 如何从子类中的方法调用子类中被覆盖的父方法?
- fastapi - 如何在 fastapi 中定义具有多个 api 密钥的自定义安全性?
- apache - 特定命名文件的 mod_rewrite 重定向导致循环
- r - 如何使用日期在一个图表中更改 x 轴间隔?(ggplot)
- django-forms - Easy - 过滤请求用户 ModelForm 选择
- azure-active-directory - Azure AD 多回复 URL
- typescript - 如何防止我的 Vue 构建由于 Typescript 错误而失败
- php - PHP Move_uploaded_file 函数不起作用
- python - 正在发生缩进错误,我似乎看不到是什么导致了错误