Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is preferred, return const double& OR return double

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; }
}
like image 209
lyxera Avatar asked Nov 06 '09 02:11

lyxera


People also ask

When should I return my const?

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).

Can return type be const?

(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].

What is double const?

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; )

What does it mean to return a const type from a function?

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.


1 Answers

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)

like image 78
cletus Avatar answered Sep 28 '22 07:09

cletus