This code looks weird:
const double square(double x) {
return x*x;
}
Common sense tells me that const
in this context means either
- the function returns a
const double
OR
- it promises not to change the
double
that was passed in. But it was passed in by value! I don't understand
OR
- I know that
const member functions
promise not to change*this
, but this is not even a member function.
Edit
What's the point to return a const double
if you can save the result in a non-const
variable and edit it??
double var = square(4.5); // no compile error
var = 0.3;
It is weird. As you say:
For a user-defined type, this would prevent you from modifying the return value:
although, as noted in the comments, this isn't allowed for a built-in type like
double
anyway. Even for user-defined types, while you probably don't want to write code like that, there's no point preventing it either.For more complicated types, returning a
const
value can actually be harmful: it inhibits move semantics, since aconst
object can't be moved from. This could hurt performance.