Recently I encounter the following code, it is an excerpt from tutorial of open-source package AMReX text
Array4<Real> const& a = fab1.array();
Dim3 lo = lbound(a);
Dim3 hi = ubound(a);
int nc = a.nComp();
for(int n=0; n<nc; n++){
for(int i=lo.x; i<=hi.x; i++){
for(int j=lo.y; j<=hi.y; j++){
for(int k=lo.z; k<=hi.z; k++){
a(i, j, k, n) = 2.0;
}
}
}
}
Array4 is a class with template which stores the data of grid points, like matrix, tensor etc. I am wondering why here variable "a" as a reference referring to a constant object can be used to modify the object's data. What are the reasons behind it? Thanks!
The tutorial says that "const means the Array4 object itself cannot be modified to point to other data". So why Array4 object can be modified here?
operator()
is markedconst
but returns a non-const reference. This violates the principle of least astonishment. That phrase in the tutorial, "cannot point to other data", doesn't make sense - the class is not pointer-like, it stores its own data and cannot be made to "point to other data", const or no const.const
, and the sense ofconst
here functions rather like areadonly
object variable in C# or VB.