///////////////////////////////////////
class A {
...
const double funA(void)
{...}
};
A a;
double x = a.funA();
// although the intention is to
// enforce the return value to be const and cannot be
// modified, it has little effect in the real world.
class A2 {
...
double funB(void)
{...}
};
///////////////////////////////////////
class A {
void setA(const double d)
{ // now you cannot change the value of d, so what?
// From my point of view, it is NOT a good practice to change the pass-in parameter
// in this case, unless you want the caller to receive that change
// instead, you can do
// const double dPassIn = d;
/ /then use dPassIn instead.
...
}
};
class A2 {
void setB(double d)
{...}
};
//////////////////////////////////////
From my understanding, we should prefer to
using A2::funB
and A2::setB
because the const used in
both A::funA
and A::setA
has little meaning.
// Update //
FMOD_RESULT F_API EventSystem::getReverbPresetByIndex(const int index,
FMOD_REVERB_PROPERTIES *props, char **name = 0);
I consider FMOD is a well-designed package and it does use const int
inside function parameter list.
Now, I agree that the A::setA(const double d)
has its edge.
When returning by value the constant has no effect as it cannot be enforced anyway. Some compilers issue a warning. However it DOES make sense to return a pointer/reference to constant data.
When passing an argument into a function it is preferable (safer, allows for compiler optimizations) to pass it as a constant unless you absolutely need to change the data.
the const-keyword tells the Compiler "In my function setB i Wont change the Argument. If you want to Optimize for Multithreading you can use this Variable the same Time in another context, because my Work wont change it."
So i would say, in Progamming-logic, the second variant is better, like you said it has "little meaning", but in wider logic if you see what really happens, you should declare const, what is const, and dont declare const what isnt const. It is kind of a documentation the compiler understands and maybe will use to optimize your code!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With