0

When this temporary object(CTest()) is destoryed?Before entry the function(fooFunc) or after the function(fooFunc) returned?

I know the code below is not right indeed(Thank you,asmmo. ). The reason is that:

"The idea is that a function taking a non-const reference parameter is stating that it wants to modify the parameter and allowing it to go back to the caller. Doing so with a temporary is meaningless and most likely an error."

I would be thankful for any hint about this question.

class CTest;
void fooFunc(CTest&){};
fooFunc(CTest());
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
sunshilong369
  • 646
  • 1
  • 5
  • 17

1 Answers1

2

Temporaries are destroyed at the end of full-expression. In your case this means that CTest() will be destroyed after fooFunc returns.

Note, that your example is ill-formed. fooFunc's parameter should be an rvalue reference or a const lvalue reference. Supposedly you use Visual Studio. Pass the /W4 flag, so VS will emit a warning that you use a nonstandard extension (so you know about that you use something which won't compile for other compilers).

geza
  • 28,403
  • 6
  • 61
  • 135
  • Is it stated in the C++ standard that temporaries are destroyed at the end of full-expression? – sunshilong369 May 23 '20 at 11:42
  • @sunshilong369: yes, here are the exact rules: http://eel.is/c++draft/class.temporary#4, http://eel.is/c++draft/class.temporary#5 and http://eel.is/c++draft/class.temporary#6 – geza May 23 '20 at 11:45
  • At the end of full-expression? Do you mean after `function(fooFunc)` returned? – sunshilong369 May 23 '20 at 13:03
  • @sunshilong369: yes, this is the second sentence of my answer :) – geza May 23 '20 at 13:23