R
RSL
In order to let compiler catches unintended changes of a passed object
in a function, we added const, for example:
struct MyStruct
{
int Value;
};
void bar(const MyStruct * const pObj)
{
// pObj = <address of another MyStruct object>;
// pObj->Value = <some value>;
}
int main()
{
MyStruct AObj;
bar(&AObj);
}
If uncommented the two lines in bar(), the compiler should be able to
catch them.
This also works for array of (const) pointers (to const):
void foo(MyStruct const *const (PtrAry)[10])
{
// PtrAry[0] = <address of another MyStruct object>;
// PtrAry[0]->Value = <some value>;
}
int main()
{
MyStruct *AryOfPtr[10] = { &AObj };
// ...
foo(AryOfPtr);
}
However, it does not works for array-of-array:
void foobar(MyStruct* const (*PtrAry)[10])
{
// PtrAry[0][0] = <address of another MyStruct object>;
PtrAry[0][0]->Value = 20;
}
int main()
{
MyStruct *ary2[10][10];
// ...
foobar(ary2);
}
In foobar(),
PtrAry[0][0]->Value = 20;
is allowed. This is expected because MyStruct is not declared as
const.
However, if foobar() is declared as such:
void foobar(const MyStruct* const (*PtrAry)[10])
{
// PtrAry[0][0] = <address of another MyStruct object>;
// PtrAry[0][0]->Value = <some value>;
}
Compiler can catch both lines (if uncommented) but generate an error
in main (cannot convert parameter 1 from 'MyStruct *[10][10]' to
'const MyStruct *const (*)[10]')
Is it possible to declare foobar() such that PtrAry points to an
arrays of pointer to non-modifiable object.
in a function, we added const, for example:
struct MyStruct
{
int Value;
};
void bar(const MyStruct * const pObj)
{
// pObj = <address of another MyStruct object>;
// pObj->Value = <some value>;
}
int main()
{
MyStruct AObj;
bar(&AObj);
}
If uncommented the two lines in bar(), the compiler should be able to
catch them.
This also works for array of (const) pointers (to const):
void foo(MyStruct const *const (PtrAry)[10])
{
// PtrAry[0] = <address of another MyStruct object>;
// PtrAry[0]->Value = <some value>;
}
int main()
{
MyStruct *AryOfPtr[10] = { &AObj };
// ...
foo(AryOfPtr);
}
However, it does not works for array-of-array:
void foobar(MyStruct* const (*PtrAry)[10])
{
// PtrAry[0][0] = <address of another MyStruct object>;
PtrAry[0][0]->Value = 20;
}
int main()
{
MyStruct *ary2[10][10];
// ...
foobar(ary2);
}
In foobar(),
PtrAry[0][0]->Value = 20;
is allowed. This is expected because MyStruct is not declared as
const.
However, if foobar() is declared as such:
void foobar(const MyStruct* const (*PtrAry)[10])
{
// PtrAry[0][0] = <address of another MyStruct object>;
// PtrAry[0][0]->Value = <some value>;
}
Compiler can catch both lines (if uncommented) but generate an error
in main (cannot convert parameter 1 from 'MyStruct *[10][10]' to
'const MyStruct *const (*)[10]')
Is it possible to declare foobar() such that PtrAry points to an
arrays of pointer to non-modifiable object.