C++ compiler warning - returning local variable

前端 未结 3 1931
你的背包
你的背包 2020-12-09 17:40

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

reference to local variable \'tmp\' returned

Here is the

3条回答
  •  暖寄归人
    2020-12-09 18:02

    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

提交回复
热议问题