Skip to content

Instantly share code, notes, and snippets.

@alexanderchuranov
Created October 25, 2022 11:49
Show Gist options
  • Select an option

  • Save alexanderchuranov/975ba91c06ea607eeeb4c120039bd792 to your computer and use it in GitHub Desktop.

Select an option

Save alexanderchuranov/975ba91c06ea607eeeb4c120039bd792 to your computer and use it in GitHub Desktop.
Demonstrates that local variables in C++ are not destroyed before the return expression is evaluated.
// Output:
//
// creating A
// using A where A.s = 'valid test value'
// destroying A where A.s = 'valid test value'
// valid test value
#include <iostream>
struct A {
std::string s;
A () {
std::cerr << "creating A" << std::endl;
}
~A() {
std::cerr << "destroying A where A.s = '" << s << "'" << std::endl;
s = "removed";
}
};
std::string use(A const* a) {
std::cerr << "using A where A.s = '" << a->s << "'" << std::endl;
return a->s;
}
std::string f() {
A a;
a.s = "valid test value";
return use(&a);
}
int main() {
std::cout << f() << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment