0

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()?

NPS
  • 6,003
  • 11
  • 53
  • 90
  • 1
    Specifically: _"Temporary objects are destroyed at the end of the full expression they're part of."_. – YSC Feb 18 '19 at 11:48
  • @YSC Thanks, I didn't find that question. So that means I can safely use the reference to `Container::a` in `f()`? – NPS Feb 18 '19 at 11:52
  • define "safe" ^^ As-is, yes this is safe. But code tend to evolve and the next programmer might not be as cautious as you were asking here. If possible, bind temporaries only to const references. – YSC Feb 18 '19 at 11:55
  • Sorry for being imprecise, I meant "is the reference valid (because the object still exists)?". – NPS Feb 18 '19 at 11:58
  • 1
    Yes, as-is the code is safe: the reference doesn't outlive what it's bound to. – YSC Feb 18 '19 at 12:03

0 Answers0