0
struct  A {

// something

~A() { std::cout <<  "A destruct!\n"; }

};

class  refWrapper {

public:

refWrapper(const  A&  a) : a_(a) {}

~refWrapper() { std::cout <<  "refWrapper destruct!\n"; }

private:

const A& a_;

};

void  func(const  refWrapper&  ref  =  A()) {

// why ~A after ~refWrapper

// Rather than after refWrapper constructor complete

}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
lipracer
  • 11
  • 3
  • Please use the code layout tool to format your question correctly. And it's helpful to elaborate on your question with more than just a code example. – paddy Apr 28 '21 at 10:37
  • do you have code that you compiled and executed to get output different from what you expected? If so, please include a [mcve] (where is your `main`?) and actual and expected output in the question – 463035818_is_not_an_ai Apr 28 '21 at 10:40
  • What is the question? Does this answer the question? https://stackoverflow.com/questions/39718268/why-do-const-references-extend-the-lifetime-of-rvalues – ypnos Apr 28 '21 at 10:42
  • @ypnos: notice that there are 2 temporaries: a `refWrapper` which is bound to `ref`, and `A()`. – Jarod42 Apr 28 '21 at 10:49
  • outside of function call, behavior is different [Demo](http://coliru.stacked-crooked.com/a/cb17509322c6caf7). – Jarod42 Apr 28 '21 at 10:50

1 Answers1

1

With default arguments, the call

func();

is equivalent to

func(A()); // so func(refWrapper(A()));

So,

  • temporary A is created first (destroyed at end of full expression)
  • temporary refWrapper is created second (bound to parameter reference)
  • temporary refWrapper destroyed.
  • temporary A destroyed.

Notice that there is an exception for lifetime extension or parameter:

A temporary object bound to a reference parameter in a function call ([expr.call]) persists until the completion of the full-expression containing the call.

So refWrapper is destroyed at end of full expression, and not at the end of func call (which is the same moment in given example though). So destruction should be done in reverse order of construction.

Jarod42
  • 203,559
  • 14
  • 181
  • 302