Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ compiler warning - returning local variable

Tags:

c++

I'm simply trying to overload a + operator and I'm getting this compiler warning

reference to local variable 'tmp' returned

Here is the code for the overload

const Int& Int::operator+(const Int& p) const
{
    Int tmp = value + p.value;
    return tmp;
}

Here is the class

class Int{
    int value;
public:
    Int() {}    // default constructor
    Int(int v) : value(v) {}
    Int& operator=(const Int&);
    const Int& operator+(const Int&) const;
};
like image 980
trikker Avatar asked Aug 20 '09 04:08

trikker


2 Answers

You can't return a reference to a local variable. Inside the operator+() function, you're creating a local variable called tmp. It will get destroyed as soon as the function exits. You can't return a reference to that variable, because it no longer exists when the calling function gets the return value.

Change your definition of the function to:

const Int operator+(const Int&) const;

It would build without warnings and work fine too.

like image 86
Sahas Avatar answered Oct 28 '22 16:10

Sahas


What you try to do is to return a reference to a memory location that will be invalid the moment you return it.

The variable tmp will disappear when it goes out of scope (that is, when operator+ is finished).

Because your return type is Int&, not the value of tmp is returned at "return tmp" but a reference to tmp. This is not correct because tmp will not exist anymore after the method is finished!!

Solution: Do not return as reference, but as Int

like image 33
Peter Smit Avatar answered Oct 28 '22 17:10

Peter Smit