简体   繁体   中英

const class can extend lifetime of const member ref of temporary?

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

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM