Const reference with primitive types?

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Const reference with primitive types?

leogargu
Hi everybody,
 
I was wondering why a const reference is used in the function below (in rs_ellipse.cpp) for the doubles cx, a0, a1. Given that those are primitive types, what is the benefit of doing this vs say, double cx=data.center.x, or const double cx=data.center.x ?

double RS_Ellipse::areaLineIntegral() const
{
   (...)
    const double& cx=data.center.x;
    const double aE=getAngle();
    const double& a0=data.angle1;
    const double& a1=data.angle2;
   (...)
}
Reply | Threaded
Open this post in threaded view
|

Re: Const reference with primitive types?

R. van Twisk
Administrator
It looks like that the developer wanted to ensure that the value never changes since it's a const reference to a double, not a double.

So, if a other developer want's to change the double, for example a0 the compiler will prevent this en the developer will hopefully realise that he isn't allowed to do so.

On your question:
double cx=data.center.x
    vs
const double & cx=data.center.x, (assuming you forgot to add the &)

In terms of processing I can only imagine that the execution speed can be exactly the same if the compiler optimises it similar, but I guess this depends on the compiler :)
Reply | Threaded
Open this post in threaded view
|

Re: Const reference with primitive types?

leogargu
Hey, thanks for the prompt and complete response! :)

It crossed my mind too that it could be to make the code faster, which I would understand if the variables were arrays or objects, but with a double I wouldn’t know what to expect. Being new to CAD software, to me this looked like the developer was trying to save memory, but I couldn't really see the benefit in this case so I thought I was missing something...
Reply | Threaded
Open this post in threaded view
|

Re: Const reference with primitive types?

R. van Twisk
Administrator
any time!

I think most important here is that const simply means to other developer 'do not change this var'.
I personally believe that it's up to the compiler to generate optimised code.

ps: we hang out out #LibreCAD@freenode.org