Created
May 26, 2015 13:36
-
-
Save s6577t/b8929f7f36eb80dad959 to your computer and use it in GitHub Desktop.
Returning a reference to a local object is a mistake.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| > make mistake && ./mistake | |
| c++ -Wall -Wextra -std=c++14 -O0 mistake.cpp -o mistake | |
| mistake.cpp:8:10: warning: reference to stack memory associated with local variable 's' returned [-Wreturn-stack-address] | |
| return s; | |
| ^ | |
| 1 warning generated. | |
| This is a mista��8 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <string> | |
| using namespace std; | |
| string & mistake() { | |
| string s("This is a mistake."); | |
| return s; | |
| } | |
| int main() { | |
| string s = mistake(); | |
| cout << s << endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, so changing line 6 to:
string mistake() {Will fix that problem. And should be perfectly performant in any modern C++ implementation as well.