Created
October 25, 2022 11:49
-
-
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.
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
| // 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