简体   繁体   中英

C++ temporary object's lifetime

void foo(const C &);
foo(C());

In this case, temporary C object lives until the end of foo() .

But my question is:

struct C { operator int(); }
void bar(int i);
bar(C());

In that case, Does temporary C object live until the end of bar() ? If not, Is there any way to make temporary object live until the end of bar() ?

edit: Thanks to user2109558, I know the code doesn't work. Then does the following code work well?

void bar(int i);
void bar(C &&c) { bar(c); }

No!the code bar(C()); is equal to int num = C(); bar(num); int num = C(); bar(num); So , temporary C object does not live until the end of bar() you have to change bar function parameter.such as void bar(const C &) or add global C object variable eg:

C c;
void bar(int i) {
 ..... 

}

but no suggestion do it.

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