1

Imagine a scenario:

class B {
  int f2() { return 5; }
}

class A {
  B f1() { B b1(); return b1; }
}

A var;
int p = var.f1().f2();

When I call f1(), an instance of class B gets created. Then, on return, a temporary copy gets created and returned. Now my question is since I'm immediately calling f2() on that returned object, will it immediately be deleted once f2 returns? Or will it live until the end of the scope? Is there any rule describing this scenario or is it compiler dependent?

Yoh Deadfall
  • 2,711
  • 7
  • 28
  • 32
Zhani Baramidze
  • 1,407
  • 1
  • 13
  • 32
  • Have you tried to add a destructor with a print to test your hypothesis? If so, what did you see and why did it confuse you? – scohe001 Mar 26 '18 at 22:29
  • I want to know if what I saw was accidental (so called "undefined behaviour"), or governed by standards – Zhani Baramidze Mar 26 '18 at 22:32
  • 2
    You may find https://stackoverflow.com/q/584824/5987 helpful, even if it's not exactly the same question. Temporary variables will last until the end of the full expression, but not beyond. – Mark Ransom Mar 26 '18 at 22:35
  • Possible duplicate of [Why do un-named C++ objects destruct before the scope block ends?](https://stackoverflow.com/questions/2298781/why-do-un-named-c-objects-destruct-before-the-scope-block-ends) – jbp Mar 26 '18 at 22:37
  • 2
    Note that `B b1();` declares a function named `b1` that returns a `B` ([see demo](https://ideone.com/a0YLO4)). It does not declare an object named `b1` of type `B`. To do that, you need to remove the parenthesis: `B b1;` – Remy Lebeau Mar 26 '18 at 22:53

1 Answers1

3

The temporaries live until the end of the full expression, which in your case is marked by the ;. So the code is perfectly safe and the p will be initialized with 5.

See

http://en.cppreference.com/w/cpp/language/lifetime

for more details.

EDIT: your code works, aside from @Remy's comment, read about the Most vexing parse for more details.

vsoftco
  • 55,410
  • 12
  • 139
  • 252