警告:ローカル変数「temp」への参照が返されました[-Wreturn-local-addr]



Warning Reference Local Variable Temp Returned



C ++でプログラミングしていたときに、warning: reference to local variable ‘temp’ returned [-Wreturn-local-addr]間違いに遭遇しました。

これは私が間違えたソースコードです。



#include using namespace std class Date { int d, m, y public: Date(int dd = 0, int mm = 0, int yy = 0) : d(dd), m(mm), y(yy) {} Date(const Date &in) : d(in.d), m(in.m), y(in.y) {} void Print() { cout << d << '/' << m << '/' << y << endl } Date &operator++(int a) { Date temp = *this cout << 'call here1 ' << a << endl this->d++ return temp//right here. } Date operator++() { cout << 'call here2 ' << endl this->d++ return *this } } int main() { Date d(14, 3, 2014) Date d1 = d++ Date d2 = ++d d1.Print() d2.Print() d.Print() }

解決策:変更Date &operator++(int a)宛先Date operator++(int a)実行、配置&削除するだけ。

理由:元のコードでは、参照されているシンボル&関数がアドレスを返すことを意味しますが、注意してくださいtemp関数本体が終了すると、一時変数になりますtempメモリスペースのもランダムに消え、存在しないアドレスを返すことはできません。



したがって、アドレスを返すことはできません。put&削除するだけです。