Yes, similar questions have been asked before but they weren't exactly the same (or at least the answers provided weren't sufficient for me).
My general question is: what is the lifespan of a temporary object created while calling a function?
Code:
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A()
{
cout << "A()" << endl;
}
A(const A&)
{
cout << "A(const A&)" << endl;
}
A(A&&)
{
cout << "A(A&&)" << endl;
}
~A()
{
cout << "~A()" << endl;
}
};
class Container
{
public:
A& getA()
{
return a;
}
private:
A a;
};
void f(A & a)
{
cout << "f()" << endl;
}
int main()
{
f (Container().getA());
cout << "main()" << endl;
}
This yields output:
A()
f()
~A()
main()
I create a temporary instance of Container and pass a reference to its field to the function f(). The output suggests that the instance of Container starts life when f() is called, lives until the function returns and only then is destroyed. But maybe this output is a fluke.
What does the standard say? Is the reference to Container::a valid in the body of f()?