I am wondering how I can have a pointer const inside a scope, and non const outside.
I read several topics and web pages including newbie question: c++ const to non-const conversion and What's the point of const pointers? The message I heard is "If you need to cast const to non-const, it's dangerous, and your code is likely poorly designed". However, I am not sure how to overcome this :
What I have now :
void compute(const CArray<FOO> &fooArray, CArray<double> &Results)
{
Results[0] = 0.0 ;
for(INT_PTR i=0 ; i<fooArray.GetCount()-1 ; ++i)
{
const FOO *foo1 = fooArray[i] ;
DoSomething(foo1) ; //BOOL method which needs a const *FOO as parameter
const FOO *foo2 = fooArray[i+1] ;
DoSomething(foo2) ; //BOOL method which needs a const *FOO as parameter
double res = 0.0 ;
Compare(foo1, foo2, res) ; //Compare(const FOO *foo1, const FOO *foo2, double &result)
Results[i+1] = res ;
}
}
But DoSomething
is a quite greedy function, and I'd like avoiding to call it twice on the same object. So I'd like to do something similar than this :
void compute(const CArray<FOO> &fooArray, CArray<double> &Results)
{
const FOO *foo1 = fooArray[0] ;
Results[0] = 0.0 ;
DoSomething(foo1) ; //BOOL method which needs a const *FOO as parameter
for(INT_PTR i=1 ; i<fooArray.GetCount() ; ++i)
{
const FOO *foo2 = fooArray[i] ;
DoSomething(foo2) ; //BOOL method which needs a const *FOO as parameter
double res = 0.0 ;
Compare(foo1, foo2, res) ; //Compare(const FOO *foo1, const FOO *foo2, double &result)
Results[i] = res ;
*foo1 = *foo2 ; //what i would like to do, but I can't since *foo1 and *foo2 are const
}
}
I 'could' remove all the const but as mentionned in the topics I read, there is a good reason they are here : DoSomething
and Compare
are not supposed to modify *foo1
and *foo2
.