Consider the following example:
#include <iostream>
struct A
{
int n = 0;
A() { std::cout << "A()" << std::endl; }
A(const A&) { std::cout << "A(const A&)" << std::endl; }
~A() { std::cout << "~A()" << std::endl; }
};
int f(A a) { std::cout << "f()" << std::endl; return 1; }
int main()
{
A a;
std::cout << f(a) << " was returned from f(A)" << std::endl;
std::cout << "leaving main..." << std::endl;
}
I expect the output of this program to be:
A()
A(const A&)
f()
~A()
1 was returned from f(A)
leaving main...
~A()
because when the function returns, its parameters should have already been destroyed. For example, if we have the following function:
A* g(A a) { std::cout << "g()" << std::endl; return &a; }
Dereferencing the returned pointer is undefined behavior:
std::cout << g(a)->n << std::endl; // undefined behavior
But the output is:
A()
A(const A&)
f()
1 was returned from f(A)
~A()
leaving main...
~A()
I'm looking for an explanation of this behavior.