Given the following scenario, which one of the following is preferred. m_state is a member rater than a local variable.
class C
{
private:
double m_state;
public:
double state() const { return m_state; } // returns double
double& state() { return m_state; }
}
===========================================
class C
{
private:
double m_state;
public:
const double& state() const { return m_state; } // returns const double&
double& state() { return m_state; }
}
Thus, it's important to use const when returning an object by value if you want to prevent its use as an lvalue. The reason const has no meaning when you're returning a built-in type by value is that the compiler already prevents it from being an lvalue (because it's always a value, and not a variable).
(C++) const return typeThe value of a return type that is declared const cannot be changed. This is especially useful when giving a reference to a class's internals (see example #0), but can also prevent rarer errors (see example #1). Use const whenever possible [1-7].
Declaring a variable to be const means that its value cannot change; therefore it must be given a value in its declaration: const double TEMP = 98.6; // TEMP is a const double. ( Equivalent: double const TEMP = 98.6; )
const is a keyword used for variable values that will remain the same. This means that const tells the compiler to prevent modifying such variable values. The const variable is declared as: const int val = 5; An object of the class can also be constant.
I wouldn't do this:
double& state() { return m_state; }
You may as well make m_state
public if you did that. Probably what makes the most sense is:
const double & state() const { return m_state; }
Then again, when you're talking about saving the copy of a 64 bit variable (ie micro-optimization) and the fact that the latter version can be recast to whatever you want, I would just copy it:
double state() const { return m_state; }
(not that there's any true security anyway)
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