Reference to local variable '...' returned from object initializer

Viewed 85

I am trying to overload operators to add PPM images together, creating a new image. However, When trying to make a new object in the function,

PPM& PPM::operator*(const double& rhs) const {
     int height = this->getHeight();
     int width = this-> getWidth();
     int mc = this-> getMaxColorValue();
     PPM lhs;
     // ...
     return lhs;
}

And there's a bunch of other stuff, ending with return(lhs); When I try to compile the code, I get an error saying:

error: reference to local variable 'lhs' returned [-Werror=return-local-addr] PPM lhs;

What is going wrong?

2 Answers

PPM lhs; is local to the function and you cannot return a reference to a local variable. lhs will die at the end of the function and you will have a dangling reference an if it compile you enter undefined behavior land.

Your operator* is a member function. When called like this:

some_ppm * 1.2

Here, 1.2 is your double rhs.

But what is your lhs?

Looking at your function, the left hand side is not some_ppm. Take a look:

PPM& PPM::operator*(const double& rhs) const {
     // ...
     PPM lhs;
     // ...
     return lhs;
}

In this case, lhs is alway a local, new instance of a PPM.

So where is the real rhs?

Rember that when you called an overloaded operator, you effectively call the member function:

some_ppm.operator*(1.2) // actually well formed syntax

And yes you guessed it, it's this. And your operator should not return a reference to the PPM, but should instead do just like a double or an int or even a std::string and return a copy:

//v----- return by value
PPM PPM::operator*(const double& rhs) const {
    int height = this->getHeight();
    int width = this-> getWidth();
    int mc = this-> getMaxColorValue();
    PPM result;

    // ...

    return result;
}
Related