Temporary extension of life

Standard Section 12.2.5 states:

The temporal reference to the reference parameter in the function call (5.2.2) is maintained until the completion of the full expression containing the call. The temporary binding to the return value in the return function (6.6.3) is preserved until the function exits. In all these cases, temporary, created during the evaluation of the expression, the initialization of the link, with the exception of the temporary link is connected, are destroyed at the end of the full expression in which they are created, and in the opposite order of completion.

The code I'm trying to understand is:

#include <iostream> const int& foo(const int& fooRef) { return fooRef; } // #0 int main (void) { const int& numberRef = foo(5); // #1 std::cout << numberRef; // #2 return 0; } 

Line #1 creates a temporary object and is bound to the fooRef parameter foo . fooRef destroyed on line #0 . Therefore, I thought that temporary destruction should be destroyed here, since life extension is not transitive.

Questions:

  • What does until the function exits ? Does this mean untill it finished executing ?

  • Why am I getting pin 5 . Does the object temporarily exist on line #2 ?

  • How can I interpret a standard quote to figure out how this example works?

It is understood that phased atomic passage with reference to the standard. Thanks!

R. S. The accepted answer here also said the code is broken , and I do not understand why I get this output from the program.

+6
source share
2 answers

What happens until a function crashes? Does this mean until it's over?

Yes.

Why am I getting output 5. Is there a temporary object in line # 2?

Highlighting a link that is not tied to a living object is undefined behavior , so you can get 5 , as well as 42 , as well as everything else (including a crash), you just can't expect any expectations in a program that has undefined behavior .

How can I interpret a standard quote to figure out how this example works?

Pretty similar to what you have already done. A temporary connection is associated with the function parameter fooRef , which is destroyed when it returns from the function. Since this temporary is related to the return value, this object ceases to exist when the function returns. Later, you play a dangling link that gives you UB.

+3
source
  • This means that before the closing parenthesis, i.e. } .

  • You called UB, you have a dangling link.

Try the following code modification and see what it prints. He will probably print 6 because this is what was the last on the stack. Or try passing std::string instead, you may get a crash.

 int main (void) { const int& numberRef = foo(5); foo(6); std::cout << numberRef; return 0; } 
+1
source

Source: https://habr.com/ru/post/948313/


All Articles