Skip to content

Instantly share code, notes, and snippets.

@s6577t
Created May 26, 2015 13:36
Show Gist options
  • Select an option

  • Save s6577t/b8929f7f36eb80dad959 to your computer and use it in GitHub Desktop.

Select an option

Save s6577t/b8929f7f36eb80dad959 to your computer and use it in GitHub Desktop.
Returning a reference to a local object is a mistake.
> 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
#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;
}
@tonymarklove
Copy link

Yeah, so changing line 6 to:

string mistake() {

Will fix that problem. And should be perfectly performant in any modern C++ implementation as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment