user63898
user63898

Reputation: 30895

Return by const reference in c++ where the receiver function copy the value is it worth it?

i have this situation which i wander if returning by const reference dose relay save something , this function may be called hundreds of times .

i have :
General Container that returns int as const reference

struct Val
{
 public:
    Val(int& v)
    {
        iVal = v;
    }

    const int& toInt()
    {
        return iVal;
    }

private:
    int iVal;
};

function that getting the number:

Val Mo::doSomthing()
{
  Val v(444444);
  return v;
}

calling the doSomthing().toInt():

int x = 0;
class Foo {
...
....
Mo mo;
void Foo::setInt(float scaleX)
{

   x = mo.doSomthing().toInt();
   //x is class member which other functions are using it 

}
...
...
..
}

In this case is there any reason to for using const reference to save some bits?

Upvotes: 1

Views: 403

Answers (1)

Broothy
Broothy

Reputation: 721

In general for scalar types it is cheaper to return them by value. A reference (and a pointer) has near the same size (word length) as an usual scalar type. If you return an int& you return ~the same amount of data, however when you access the data referenced the running platform has to resolve the reference (access the memory referenced).

But the previous comments are right: measure it first. It is a kind of micro optimization.

Upvotes: 2

Related Questions