2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【c++】Reference to stack memory associated with local variable

Last updated at Posted at 2015-03-19

元ブログ、【c++】Reference to stack memory associated with local variable - 技術は熱いうちに打て!

掲題の警告が出ました。
どういう意味なんでしょうか?

エラーが出たコードは概ね以下の形です。

const string& Sample::getString(int a)
{
  string data { to_string(a) };
  return data;
}

return dataの部分で警告が出ます。

無効な参照の返却

問題はこのメソッド内でしか有効でないインスタンスの参照を返している事でした。

このメソッドを利用してこのインスタンスの参照を得たとしても、メソッドを抜けた時点でこのインスタンスは既に破棄されています。
だからダメだよってコンパイラが教えてくれているんですね。

対処

参照を返すのではなくデータそのものを返す様にすれば良いかと思います。

誰かのお役に立てば。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?