Why doesn't a const reference extend the life of a temporary object passed via a function?Why use “b < a ? a : b” instead of “a < b ? b : a” to implement max template?How come a non-const reference cannot bind to a temporary object?Does a const reference class member prolong the life of a temporary?How do I achieve the theoretical maximum of 4 FLOPs per cycle?Why not non-const reference to temporary objects?Temporary object and non-const referenceconst reference to temporary referenceC++11 scoping and lifetime of temporary bound to a (const) reference (GCC)Why am I using the deleted function 'void std::ref(const _Tp&&) [with _Tp = int]'Can a Second Const Reference Extend the Lifetime of a TemporaryExtending the life of a temporary object by getting a reference to a subobject

Doomsday-clock for my fantasy planet

Does bootstrapped regression allow for inference?

Need help identifying/translating a plaque in Tangier, Morocco

Prime joint compound before latex paint?

How can I plot a Farey diagram?

What does 'script /dev/null' do?

Email Account under attack (really) - anything I can do?

What is the offset in a seaplane's hull?

Manga about a female worker who got dragged into another world together with this high school girl and she was just told she's not needed anymore

Domain expired, GoDaddy holds it and is asking more money

Can a planet have a different gravitational pull depending on its location in orbit around its sun?

Where else does the Shulchan Aruch quote an authority by name?

Is there a way to make member function NOT callable from constructor?

Filling an area between two curves

COUNT(*) or MAX(id) - which is faster?

Is domain driven design an anti-SQL pattern?

How is it possible for user's password to be changed after storage was encrypted? (on OS X, Android)

Is a vector space a subspace of itself?

Calculate Levenshtein distance between two strings in Python

Are white and non-white police officers equally likely to kill black suspects?

Why is my log file so massive? 22gb. I am running log backups

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

Landlord wants to switch my lease to a "Land contract" to "get back at the city"

What is GPS' 19 year rollover and does it present a cybersecurity issue?



Why doesn't a const reference extend the life of a temporary object passed via a function?


Why use “b < a ? a : b” instead of “a < b ? b : a” to implement max template?How come a non-const reference cannot bind to a temporary object?Does a const reference class member prolong the life of a temporary?How do I achieve the theoretical maximum of 4 FLOPs per cycle?Why not non-const reference to temporary objects?Temporary object and non-const referenceconst reference to temporary referenceC++11 scoping and lifetime of temporary bound to a (const) reference (GCC)Why am I using the deleted function 'void std::ref(const _Tp&&) [with _Tp = int]'Can a Second Const Reference Extend the Lifetime of a TemporaryExtending the life of a temporary object by getting a reference to a subobject






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








22















In the following simple example, why can't ref2 be bound to the result of min(x,y+1)?



#include <cstdio>
template< typename T > const T& min(const T& a, const T& b) return a < b ? a : b ;

int main()
int x = 10, y = 2;
const int& ref = min(x,y); //OK
const int& ref2 = min(x,y+1); //NOT OK, WHY?
return ref2; // Compiles to return 0



live example - produces:



main:
xor eax, eax
ret









share|improve this question



















  • 7





    This program produces no output and exits with code 0. With -O3 optimization flag all the statements inside of main are discarded.

    – VTT
    22 hours ago






  • 3





    What error does it give?

    – fredrik
    22 hours ago






  • 5





    This is actually a very interesting question. I'll tag language lawyer and hope one of the chiefs picks this one up. I've neither the time nor the expertise. It's all to do with the fact that lifetime extension is not transitive, and where the original objects are located. Go on @StoryTeller.

    – Bathsheba
    22 hours ago







  • 4





    @Bathsheba Could you quickly explain why b < a ? b : a that advantageous?

    – lubgr
    22 hours ago






  • 4





    @Michiel The thing is, if the binding was direct (e.g. if min was returning by value), ref2 would extend the lifetime of the bound temporary to that of itself. Hence the question, I guess.

    – Angew
    22 hours ago

















22















In the following simple example, why can't ref2 be bound to the result of min(x,y+1)?



#include <cstdio>
template< typename T > const T& min(const T& a, const T& b) return a < b ? a : b ;

int main()
int x = 10, y = 2;
const int& ref = min(x,y); //OK
const int& ref2 = min(x,y+1); //NOT OK, WHY?
return ref2; // Compiles to return 0



live example - produces:



main:
xor eax, eax
ret









share|improve this question



















  • 7





    This program produces no output and exits with code 0. With -O3 optimization flag all the statements inside of main are discarded.

    – VTT
    22 hours ago






  • 3





    What error does it give?

    – fredrik
    22 hours ago






  • 5





    This is actually a very interesting question. I'll tag language lawyer and hope one of the chiefs picks this one up. I've neither the time nor the expertise. It's all to do with the fact that lifetime extension is not transitive, and where the original objects are located. Go on @StoryTeller.

    – Bathsheba
    22 hours ago







  • 4





    @Bathsheba Could you quickly explain why b < a ? b : a that advantageous?

    – lubgr
    22 hours ago






  • 4





    @Michiel The thing is, if the binding was direct (e.g. if min was returning by value), ref2 would extend the lifetime of the bound temporary to that of itself. Hence the question, I guess.

    – Angew
    22 hours ago













22












22








22


3






In the following simple example, why can't ref2 be bound to the result of min(x,y+1)?



#include <cstdio>
template< typename T > const T& min(const T& a, const T& b) return a < b ? a : b ;

int main()
int x = 10, y = 2;
const int& ref = min(x,y); //OK
const int& ref2 = min(x,y+1); //NOT OK, WHY?
return ref2; // Compiles to return 0



live example - produces:



main:
xor eax, eax
ret









share|improve this question
















In the following simple example, why can't ref2 be bound to the result of min(x,y+1)?



#include <cstdio>
template< typename T > const T& min(const T& a, const T& b) return a < b ? a : b ;

int main()
int x = 10, y = 2;
const int& ref = min(x,y); //OK
const int& ref2 = min(x,y+1); //NOT OK, WHY?
return ref2; // Compiles to return 0



live example - produces:



main:
xor eax, eax
ret






c++ language-lawyer temporary-objects






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 15 hours ago









Boann

37.4k1290122




37.4k1290122










asked 22 hours ago









Khurshid NormuradovKhurshid Normuradov

402310




402310







  • 7





    This program produces no output and exits with code 0. With -O3 optimization flag all the statements inside of main are discarded.

    – VTT
    22 hours ago






  • 3





    What error does it give?

    – fredrik
    22 hours ago






  • 5





    This is actually a very interesting question. I'll tag language lawyer and hope one of the chiefs picks this one up. I've neither the time nor the expertise. It's all to do with the fact that lifetime extension is not transitive, and where the original objects are located. Go on @StoryTeller.

    – Bathsheba
    22 hours ago







  • 4





    @Bathsheba Could you quickly explain why b < a ? b : a that advantageous?

    – lubgr
    22 hours ago






  • 4





    @Michiel The thing is, if the binding was direct (e.g. if min was returning by value), ref2 would extend the lifetime of the bound temporary to that of itself. Hence the question, I guess.

    – Angew
    22 hours ago












  • 7





    This program produces no output and exits with code 0. With -O3 optimization flag all the statements inside of main are discarded.

    – VTT
    22 hours ago






  • 3





    What error does it give?

    – fredrik
    22 hours ago






  • 5





    This is actually a very interesting question. I'll tag language lawyer and hope one of the chiefs picks this one up. I've neither the time nor the expertise. It's all to do with the fact that lifetime extension is not transitive, and where the original objects are located. Go on @StoryTeller.

    – Bathsheba
    22 hours ago







  • 4





    @Bathsheba Could you quickly explain why b < a ? b : a that advantageous?

    – lubgr
    22 hours ago






  • 4





    @Michiel The thing is, if the binding was direct (e.g. if min was returning by value), ref2 would extend the lifetime of the bound temporary to that of itself. Hence the question, I guess.

    – Angew
    22 hours ago







7




7





This program produces no output and exits with code 0. With -O3 optimization flag all the statements inside of main are discarded.

– VTT
22 hours ago





This program produces no output and exits with code 0. With -O3 optimization flag all the statements inside of main are discarded.

– VTT
22 hours ago




3




3





What error does it give?

– fredrik
22 hours ago





What error does it give?

– fredrik
22 hours ago




5




5





This is actually a very interesting question. I'll tag language lawyer and hope one of the chiefs picks this one up. I've neither the time nor the expertise. It's all to do with the fact that lifetime extension is not transitive, and where the original objects are located. Go on @StoryTeller.

– Bathsheba
22 hours ago






This is actually a very interesting question. I'll tag language lawyer and hope one of the chiefs picks this one up. I've neither the time nor the expertise. It's all to do with the fact that lifetime extension is not transitive, and where the original objects are located. Go on @StoryTeller.

– Bathsheba
22 hours ago





4




4





@Bathsheba Could you quickly explain why b < a ? b : a that advantageous?

– lubgr
22 hours ago





@Bathsheba Could you quickly explain why b < a ? b : a that advantageous?

– lubgr
22 hours ago




4




4





@Michiel The thing is, if the binding was direct (e.g. if min was returning by value), ref2 would extend the lifetime of the bound temporary to that of itself. Hence the question, I guess.

– Angew
22 hours ago





@Michiel The thing is, if the binding was direct (e.g. if min was returning by value), ref2 would extend the lifetime of the bound temporary to that of itself. Hence the question, I guess.

– Angew
22 hours ago












3 Answers
3






active

oldest

votes


















25














It's by design. In a nutshell, only the named reference to which the temporary is bound directly will extend its lifetime.




[class.temporary]



5 There are three contexts in which temporaries are destroyed at a
different point than the end of the full-expression. [...]



6 The third context is when a reference is bound to a temporary.
The temporary to which the reference is bound or the temporary that is
the complete object of a subobject to which the reference is bound
persists for the lifetime of the reference except:



  • A temporary object bound to a reference parameter in a function call persists until the completion of the full-expression containing
    the call.

  • The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed
    at the end of the full-expression in the return statement.

  • [...]



You didn't bind directly to ref2, and you even pass it via a return statement. The standard explicitly says it won't extend the lifetime. In part to make certain optimizations possible. But ultimately, because keeping track of which temporary should be extended when a reference is passed in and out of functions is intractable in general.



Since compilers may optimize aggressively on the assumption that your program exhibits no undefined behavior, you see a possible manifestation of that. Accessing a value outside its lifetime is undefined, this is what return ref2; does, and since the behavior is undefined, simply returning zero is a valid behavior to exhibit. No contract is broken by the compiler.






share|improve this answer

























  • Thx a lot. I wrongly thought that, y+1 temporary object bind to b and it's live extends via return function. .

    – Khurshid Normuradov
    20 hours ago


















13














This is intentional. A reference can only extend the lifetime of a temporary when it is bound to that temporary directly. In your code, you are binding ref2 to the result of min, which is a reference. It doesn't matter that that reference references a temporary. Only b extends the lifetime of the temporary; it doesn't matter that ref2 also refers to that same temporary.



Another way to look at it: You can't optionally have lifetime extension. It's a static property. If ref2 would do the Correct Thingtm, then depending on the runtime values of x and y+1 the lifetime is extended or not. Not something the compiler is able to do.






share|improve this answer






























    5














    I will answer the question first, and then provide some context for the answer. The current working draft contains the following wording:




    The temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference if the glvalue to which the reference is bound was obtained through one of the following:



    • a temporary materialization conversion ([conv.rval]),


    • ( expression ), where expression is one of these expressions,

    • subscripting ([expr.sub]) of an array operand, where that operand is one of these expressions,

    • a class member access ([expr.ref]) using the . operator where the left operand is one of these expressions and the right operand designates a non-static data member of non-reference type,

    • a pointer-to-member operation ([expr.mptr.oper]) using the .* operator where the left operand is one of these expressions and the right operand is a pointer to data member of non-reference type,

    • a const_­cast ([expr.const.cast]), static_­cast ([expr.static.cast]), dynamic_­cast ([expr.dynamic.cast]), or reinterpret_­cast ([expr.reinterpret.cast])
      converting, without a user-defined conversion, a glvalue operand that is one of these expressions to a glvalue that refers to the object designated by the operand, or to its complete object or a subobject thereof,

    • a conditional expression ([expr.cond]) that is a glvalue where the second or third operand is one of these expressions, or

    • a comma expression ([expr.comma]) that is a glvalue where the right operand is one of these expressions.



    According to this, when a reference is bound to a glvalue returned from a function call, lifetime extension does not occur, because the glvalue was obtained from the function call, which is not one of the permitted expressions for lifetime extension.



    The lifetime of the y+1 temporary is extended once when bound to the reference parameter b. Here, the prvalue y+1 is materialized to yield an xvalue, and the reference is bound to the result of the temporary materialization conversion; lifetime extension thus occurs. When the min function returns, however, ref2 is bound to the result of the call, and lifetime extension does not occur here. Therefore, the y+1 temporary is destroyed at the end of the definition of ref2, and ref2 becomes a dangling reference.




    There has historically been some confusion on this topic. It is well-known that the OP's code and similar code result in a dangling reference, but the standard text, even as of C++17, did not provide an unambiguous explanation as to why.



    It is often claimed that lifetime extension only applies when the reference binds "directly" to the temporary, but the standard has never said anything to that effect. Indeed, the standard defines what it means for a reference to "bind directly", and that definition (e.g., const std::string& s = "foo"; is an indirect reference binding) is clearly not relevant here.



    Rakete1111 has said in a comment elsewhere on SO that lifetime extension only applies when the reference binds to a prvalue (rather than some glvalue that was obtained through a previous reference binding to that temporary object); they appear to be saying something similar here by "bound ... directly". However, there is no textual support for this theory. Indeed, code like the following has sometimes been considered to trigger lifetime extension:



    struct S int x; ;
    const int& r = S42.x;


    However, in C++14, the expression S42.x became an xvalue, so if lifetime extension applies here, then it is not because the reference binds to a prvalue.



    One might instead claim that lifetime extension only applies once, and binding any other references to the same object do not further extend its lifetime. This would explain why the OP's code creates a dangling reference, without preventing lifetime extension in the S42.x case. However, there is no statement to this effect in the standard, either.



    StoryTeller has also said here that the reference must bind directly, but I don't know what he means by that, either. He cites standards text indicating that binding a reference to a temporary in a return statement doesn't extend its lifetime. However, that statement seems to be intended to apply to the case where the temporary in question is created by the full-expression in the return statement, since it says the temporary will be destroyed at the end of that full-expression. Clearly that's not the case for the y+1 temporary, which will instead be destroyed at the end of the full-expression containing the call to min. Thus, I tend to think that this statement was not intended to apply to cases like that in the question. Instead, its effect, together with the other limitations on lifetime extension, is to prevent any temporary object's lifetime from being extended beyond the block scope in which it was created. But this would not prevent the y+1 temporary in the question from surviving until the end of main.



    Thus the question remains: what is the principle that explains why the binding of ref2 to the temporary in the question doesn't extend that temporary's lifetime?



    The wording from the current working draft that I cited earlier was introduced by the resolution of CWG 1299, which was opened in 2011 but only resolved recently (not in time for C++17). In a sense, it clarifies the intuition that the reference must bind "directly", by delineating those cases where the binding is "direct" enough for lifetime extension to occur; it is not, however, so restrictive as to only allow it when the reference binds to a prvalue. It permits lifetime extension in the S42.x case.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55567962%2fwhy-doesnt-a-const-reference-extend-the-life-of-a-temporary-object-passed-via-a%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      25














      It's by design. In a nutshell, only the named reference to which the temporary is bound directly will extend its lifetime.




      [class.temporary]



      5 There are three contexts in which temporaries are destroyed at a
      different point than the end of the full-expression. [...]



      6 The third context is when a reference is bound to a temporary.
      The temporary to which the reference is bound or the temporary that is
      the complete object of a subobject to which the reference is bound
      persists for the lifetime of the reference except:



      • A temporary object bound to a reference parameter in a function call persists until the completion of the full-expression containing
        the call.

      • The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed
        at the end of the full-expression in the return statement.

      • [...]



      You didn't bind directly to ref2, and you even pass it via a return statement. The standard explicitly says it won't extend the lifetime. In part to make certain optimizations possible. But ultimately, because keeping track of which temporary should be extended when a reference is passed in and out of functions is intractable in general.



      Since compilers may optimize aggressively on the assumption that your program exhibits no undefined behavior, you see a possible manifestation of that. Accessing a value outside its lifetime is undefined, this is what return ref2; does, and since the behavior is undefined, simply returning zero is a valid behavior to exhibit. No contract is broken by the compiler.






      share|improve this answer

























      • Thx a lot. I wrongly thought that, y+1 temporary object bind to b and it's live extends via return function. .

        – Khurshid Normuradov
        20 hours ago















      25














      It's by design. In a nutshell, only the named reference to which the temporary is bound directly will extend its lifetime.




      [class.temporary]



      5 There are three contexts in which temporaries are destroyed at a
      different point than the end of the full-expression. [...]



      6 The third context is when a reference is bound to a temporary.
      The temporary to which the reference is bound or the temporary that is
      the complete object of a subobject to which the reference is bound
      persists for the lifetime of the reference except:



      • A temporary object bound to a reference parameter in a function call persists until the completion of the full-expression containing
        the call.

      • The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed
        at the end of the full-expression in the return statement.

      • [...]



      You didn't bind directly to ref2, and you even pass it via a return statement. The standard explicitly says it won't extend the lifetime. In part to make certain optimizations possible. But ultimately, because keeping track of which temporary should be extended when a reference is passed in and out of functions is intractable in general.



      Since compilers may optimize aggressively on the assumption that your program exhibits no undefined behavior, you see a possible manifestation of that. Accessing a value outside its lifetime is undefined, this is what return ref2; does, and since the behavior is undefined, simply returning zero is a valid behavior to exhibit. No contract is broken by the compiler.






      share|improve this answer

























      • Thx a lot. I wrongly thought that, y+1 temporary object bind to b and it's live extends via return function. .

        – Khurshid Normuradov
        20 hours ago













      25












      25








      25







      It's by design. In a nutshell, only the named reference to which the temporary is bound directly will extend its lifetime.




      [class.temporary]



      5 There are three contexts in which temporaries are destroyed at a
      different point than the end of the full-expression. [...]



      6 The third context is when a reference is bound to a temporary.
      The temporary to which the reference is bound or the temporary that is
      the complete object of a subobject to which the reference is bound
      persists for the lifetime of the reference except:



      • A temporary object bound to a reference parameter in a function call persists until the completion of the full-expression containing
        the call.

      • The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed
        at the end of the full-expression in the return statement.

      • [...]



      You didn't bind directly to ref2, and you even pass it via a return statement. The standard explicitly says it won't extend the lifetime. In part to make certain optimizations possible. But ultimately, because keeping track of which temporary should be extended when a reference is passed in and out of functions is intractable in general.



      Since compilers may optimize aggressively on the assumption that your program exhibits no undefined behavior, you see a possible manifestation of that. Accessing a value outside its lifetime is undefined, this is what return ref2; does, and since the behavior is undefined, simply returning zero is a valid behavior to exhibit. No contract is broken by the compiler.






      share|improve this answer















      It's by design. In a nutshell, only the named reference to which the temporary is bound directly will extend its lifetime.




      [class.temporary]



      5 There are three contexts in which temporaries are destroyed at a
      different point than the end of the full-expression. [...]



      6 The third context is when a reference is bound to a temporary.
      The temporary to which the reference is bound or the temporary that is
      the complete object of a subobject to which the reference is bound
      persists for the lifetime of the reference except:



      • A temporary object bound to a reference parameter in a function call persists until the completion of the full-expression containing
        the call.

      • The lifetime of a temporary bound to the returned value in a function return statement is not extended; the temporary is destroyed
        at the end of the full-expression in the return statement.

      • [...]



      You didn't bind directly to ref2, and you even pass it via a return statement. The standard explicitly says it won't extend the lifetime. In part to make certain optimizations possible. But ultimately, because keeping track of which temporary should be extended when a reference is passed in and out of functions is intractable in general.



      Since compilers may optimize aggressively on the assumption that your program exhibits no undefined behavior, you see a possible manifestation of that. Accessing a value outside its lifetime is undefined, this is what return ref2; does, and since the behavior is undefined, simply returning zero is a valid behavior to exhibit. No contract is broken by the compiler.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 22 hours ago

























      answered 22 hours ago









      StoryTellerStoryTeller

      105k13220284




      105k13220284












      • Thx a lot. I wrongly thought that, y+1 temporary object bind to b and it's live extends via return function. .

        – Khurshid Normuradov
        20 hours ago

















      • Thx a lot. I wrongly thought that, y+1 temporary object bind to b and it's live extends via return function. .

        – Khurshid Normuradov
        20 hours ago
















      Thx a lot. I wrongly thought that, y+1 temporary object bind to b and it's live extends via return function. .

      – Khurshid Normuradov
      20 hours ago





      Thx a lot. I wrongly thought that, y+1 temporary object bind to b and it's live extends via return function. .

      – Khurshid Normuradov
      20 hours ago













      13














      This is intentional. A reference can only extend the lifetime of a temporary when it is bound to that temporary directly. In your code, you are binding ref2 to the result of min, which is a reference. It doesn't matter that that reference references a temporary. Only b extends the lifetime of the temporary; it doesn't matter that ref2 also refers to that same temporary.



      Another way to look at it: You can't optionally have lifetime extension. It's a static property. If ref2 would do the Correct Thingtm, then depending on the runtime values of x and y+1 the lifetime is extended or not. Not something the compiler is able to do.






      share|improve this answer



























        13














        This is intentional. A reference can only extend the lifetime of a temporary when it is bound to that temporary directly. In your code, you are binding ref2 to the result of min, which is a reference. It doesn't matter that that reference references a temporary. Only b extends the lifetime of the temporary; it doesn't matter that ref2 also refers to that same temporary.



        Another way to look at it: You can't optionally have lifetime extension. It's a static property. If ref2 would do the Correct Thingtm, then depending on the runtime values of x and y+1 the lifetime is extended or not. Not something the compiler is able to do.






        share|improve this answer

























          13












          13








          13







          This is intentional. A reference can only extend the lifetime of a temporary when it is bound to that temporary directly. In your code, you are binding ref2 to the result of min, which is a reference. It doesn't matter that that reference references a temporary. Only b extends the lifetime of the temporary; it doesn't matter that ref2 also refers to that same temporary.



          Another way to look at it: You can't optionally have lifetime extension. It's a static property. If ref2 would do the Correct Thingtm, then depending on the runtime values of x and y+1 the lifetime is extended or not. Not something the compiler is able to do.






          share|improve this answer













          This is intentional. A reference can only extend the lifetime of a temporary when it is bound to that temporary directly. In your code, you are binding ref2 to the result of min, which is a reference. It doesn't matter that that reference references a temporary. Only b extends the lifetime of the temporary; it doesn't matter that ref2 also refers to that same temporary.



          Another way to look at it: You can't optionally have lifetime extension. It's a static property. If ref2 would do the Correct Thingtm, then depending on the runtime values of x and y+1 the lifetime is extended or not. Not something the compiler is able to do.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 22 hours ago









          Rakete1111Rakete1111

          35.3k1084120




          35.3k1084120





















              5














              I will answer the question first, and then provide some context for the answer. The current working draft contains the following wording:




              The temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference if the glvalue to which the reference is bound was obtained through one of the following:



              • a temporary materialization conversion ([conv.rval]),


              • ( expression ), where expression is one of these expressions,

              • subscripting ([expr.sub]) of an array operand, where that operand is one of these expressions,

              • a class member access ([expr.ref]) using the . operator where the left operand is one of these expressions and the right operand designates a non-static data member of non-reference type,

              • a pointer-to-member operation ([expr.mptr.oper]) using the .* operator where the left operand is one of these expressions and the right operand is a pointer to data member of non-reference type,

              • a const_­cast ([expr.const.cast]), static_­cast ([expr.static.cast]), dynamic_­cast ([expr.dynamic.cast]), or reinterpret_­cast ([expr.reinterpret.cast])
                converting, without a user-defined conversion, a glvalue operand that is one of these expressions to a glvalue that refers to the object designated by the operand, or to its complete object or a subobject thereof,

              • a conditional expression ([expr.cond]) that is a glvalue where the second or third operand is one of these expressions, or

              • a comma expression ([expr.comma]) that is a glvalue where the right operand is one of these expressions.



              According to this, when a reference is bound to a glvalue returned from a function call, lifetime extension does not occur, because the glvalue was obtained from the function call, which is not one of the permitted expressions for lifetime extension.



              The lifetime of the y+1 temporary is extended once when bound to the reference parameter b. Here, the prvalue y+1 is materialized to yield an xvalue, and the reference is bound to the result of the temporary materialization conversion; lifetime extension thus occurs. When the min function returns, however, ref2 is bound to the result of the call, and lifetime extension does not occur here. Therefore, the y+1 temporary is destroyed at the end of the definition of ref2, and ref2 becomes a dangling reference.




              There has historically been some confusion on this topic. It is well-known that the OP's code and similar code result in a dangling reference, but the standard text, even as of C++17, did not provide an unambiguous explanation as to why.



              It is often claimed that lifetime extension only applies when the reference binds "directly" to the temporary, but the standard has never said anything to that effect. Indeed, the standard defines what it means for a reference to "bind directly", and that definition (e.g., const std::string& s = "foo"; is an indirect reference binding) is clearly not relevant here.



              Rakete1111 has said in a comment elsewhere on SO that lifetime extension only applies when the reference binds to a prvalue (rather than some glvalue that was obtained through a previous reference binding to that temporary object); they appear to be saying something similar here by "bound ... directly". However, there is no textual support for this theory. Indeed, code like the following has sometimes been considered to trigger lifetime extension:



              struct S int x; ;
              const int& r = S42.x;


              However, in C++14, the expression S42.x became an xvalue, so if lifetime extension applies here, then it is not because the reference binds to a prvalue.



              One might instead claim that lifetime extension only applies once, and binding any other references to the same object do not further extend its lifetime. This would explain why the OP's code creates a dangling reference, without preventing lifetime extension in the S42.x case. However, there is no statement to this effect in the standard, either.



              StoryTeller has also said here that the reference must bind directly, but I don't know what he means by that, either. He cites standards text indicating that binding a reference to a temporary in a return statement doesn't extend its lifetime. However, that statement seems to be intended to apply to the case where the temporary in question is created by the full-expression in the return statement, since it says the temporary will be destroyed at the end of that full-expression. Clearly that's not the case for the y+1 temporary, which will instead be destroyed at the end of the full-expression containing the call to min. Thus, I tend to think that this statement was not intended to apply to cases like that in the question. Instead, its effect, together with the other limitations on lifetime extension, is to prevent any temporary object's lifetime from being extended beyond the block scope in which it was created. But this would not prevent the y+1 temporary in the question from surviving until the end of main.



              Thus the question remains: what is the principle that explains why the binding of ref2 to the temporary in the question doesn't extend that temporary's lifetime?



              The wording from the current working draft that I cited earlier was introduced by the resolution of CWG 1299, which was opened in 2011 but only resolved recently (not in time for C++17). In a sense, it clarifies the intuition that the reference must bind "directly", by delineating those cases where the binding is "direct" enough for lifetime extension to occur; it is not, however, so restrictive as to only allow it when the reference binds to a prvalue. It permits lifetime extension in the S42.x case.






              share|improve this answer



























                5














                I will answer the question first, and then provide some context for the answer. The current working draft contains the following wording:




                The temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference if the glvalue to which the reference is bound was obtained through one of the following:



                • a temporary materialization conversion ([conv.rval]),


                • ( expression ), where expression is one of these expressions,

                • subscripting ([expr.sub]) of an array operand, where that operand is one of these expressions,

                • a class member access ([expr.ref]) using the . operator where the left operand is one of these expressions and the right operand designates a non-static data member of non-reference type,

                • a pointer-to-member operation ([expr.mptr.oper]) using the .* operator where the left operand is one of these expressions and the right operand is a pointer to data member of non-reference type,

                • a const_­cast ([expr.const.cast]), static_­cast ([expr.static.cast]), dynamic_­cast ([expr.dynamic.cast]), or reinterpret_­cast ([expr.reinterpret.cast])
                  converting, without a user-defined conversion, a glvalue operand that is one of these expressions to a glvalue that refers to the object designated by the operand, or to its complete object or a subobject thereof,

                • a conditional expression ([expr.cond]) that is a glvalue where the second or third operand is one of these expressions, or

                • a comma expression ([expr.comma]) that is a glvalue where the right operand is one of these expressions.



                According to this, when a reference is bound to a glvalue returned from a function call, lifetime extension does not occur, because the glvalue was obtained from the function call, which is not one of the permitted expressions for lifetime extension.



                The lifetime of the y+1 temporary is extended once when bound to the reference parameter b. Here, the prvalue y+1 is materialized to yield an xvalue, and the reference is bound to the result of the temporary materialization conversion; lifetime extension thus occurs. When the min function returns, however, ref2 is bound to the result of the call, and lifetime extension does not occur here. Therefore, the y+1 temporary is destroyed at the end of the definition of ref2, and ref2 becomes a dangling reference.




                There has historically been some confusion on this topic. It is well-known that the OP's code and similar code result in a dangling reference, but the standard text, even as of C++17, did not provide an unambiguous explanation as to why.



                It is often claimed that lifetime extension only applies when the reference binds "directly" to the temporary, but the standard has never said anything to that effect. Indeed, the standard defines what it means for a reference to "bind directly", and that definition (e.g., const std::string& s = "foo"; is an indirect reference binding) is clearly not relevant here.



                Rakete1111 has said in a comment elsewhere on SO that lifetime extension only applies when the reference binds to a prvalue (rather than some glvalue that was obtained through a previous reference binding to that temporary object); they appear to be saying something similar here by "bound ... directly". However, there is no textual support for this theory. Indeed, code like the following has sometimes been considered to trigger lifetime extension:



                struct S int x; ;
                const int& r = S42.x;


                However, in C++14, the expression S42.x became an xvalue, so if lifetime extension applies here, then it is not because the reference binds to a prvalue.



                One might instead claim that lifetime extension only applies once, and binding any other references to the same object do not further extend its lifetime. This would explain why the OP's code creates a dangling reference, without preventing lifetime extension in the S42.x case. However, there is no statement to this effect in the standard, either.



                StoryTeller has also said here that the reference must bind directly, but I don't know what he means by that, either. He cites standards text indicating that binding a reference to a temporary in a return statement doesn't extend its lifetime. However, that statement seems to be intended to apply to the case where the temporary in question is created by the full-expression in the return statement, since it says the temporary will be destroyed at the end of that full-expression. Clearly that's not the case for the y+1 temporary, which will instead be destroyed at the end of the full-expression containing the call to min. Thus, I tend to think that this statement was not intended to apply to cases like that in the question. Instead, its effect, together with the other limitations on lifetime extension, is to prevent any temporary object's lifetime from being extended beyond the block scope in which it was created. But this would not prevent the y+1 temporary in the question from surviving until the end of main.



                Thus the question remains: what is the principle that explains why the binding of ref2 to the temporary in the question doesn't extend that temporary's lifetime?



                The wording from the current working draft that I cited earlier was introduced by the resolution of CWG 1299, which was opened in 2011 but only resolved recently (not in time for C++17). In a sense, it clarifies the intuition that the reference must bind "directly", by delineating those cases where the binding is "direct" enough for lifetime extension to occur; it is not, however, so restrictive as to only allow it when the reference binds to a prvalue. It permits lifetime extension in the S42.x case.






                share|improve this answer

























                  5












                  5








                  5







                  I will answer the question first, and then provide some context for the answer. The current working draft contains the following wording:




                  The temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference if the glvalue to which the reference is bound was obtained through one of the following:



                  • a temporary materialization conversion ([conv.rval]),


                  • ( expression ), where expression is one of these expressions,

                  • subscripting ([expr.sub]) of an array operand, where that operand is one of these expressions,

                  • a class member access ([expr.ref]) using the . operator where the left operand is one of these expressions and the right operand designates a non-static data member of non-reference type,

                  • a pointer-to-member operation ([expr.mptr.oper]) using the .* operator where the left operand is one of these expressions and the right operand is a pointer to data member of non-reference type,

                  • a const_­cast ([expr.const.cast]), static_­cast ([expr.static.cast]), dynamic_­cast ([expr.dynamic.cast]), or reinterpret_­cast ([expr.reinterpret.cast])
                    converting, without a user-defined conversion, a glvalue operand that is one of these expressions to a glvalue that refers to the object designated by the operand, or to its complete object or a subobject thereof,

                  • a conditional expression ([expr.cond]) that is a glvalue where the second or third operand is one of these expressions, or

                  • a comma expression ([expr.comma]) that is a glvalue where the right operand is one of these expressions.



                  According to this, when a reference is bound to a glvalue returned from a function call, lifetime extension does not occur, because the glvalue was obtained from the function call, which is not one of the permitted expressions for lifetime extension.



                  The lifetime of the y+1 temporary is extended once when bound to the reference parameter b. Here, the prvalue y+1 is materialized to yield an xvalue, and the reference is bound to the result of the temporary materialization conversion; lifetime extension thus occurs. When the min function returns, however, ref2 is bound to the result of the call, and lifetime extension does not occur here. Therefore, the y+1 temporary is destroyed at the end of the definition of ref2, and ref2 becomes a dangling reference.




                  There has historically been some confusion on this topic. It is well-known that the OP's code and similar code result in a dangling reference, but the standard text, even as of C++17, did not provide an unambiguous explanation as to why.



                  It is often claimed that lifetime extension only applies when the reference binds "directly" to the temporary, but the standard has never said anything to that effect. Indeed, the standard defines what it means for a reference to "bind directly", and that definition (e.g., const std::string& s = "foo"; is an indirect reference binding) is clearly not relevant here.



                  Rakete1111 has said in a comment elsewhere on SO that lifetime extension only applies when the reference binds to a prvalue (rather than some glvalue that was obtained through a previous reference binding to that temporary object); they appear to be saying something similar here by "bound ... directly". However, there is no textual support for this theory. Indeed, code like the following has sometimes been considered to trigger lifetime extension:



                  struct S int x; ;
                  const int& r = S42.x;


                  However, in C++14, the expression S42.x became an xvalue, so if lifetime extension applies here, then it is not because the reference binds to a prvalue.



                  One might instead claim that lifetime extension only applies once, and binding any other references to the same object do not further extend its lifetime. This would explain why the OP's code creates a dangling reference, without preventing lifetime extension in the S42.x case. However, there is no statement to this effect in the standard, either.



                  StoryTeller has also said here that the reference must bind directly, but I don't know what he means by that, either. He cites standards text indicating that binding a reference to a temporary in a return statement doesn't extend its lifetime. However, that statement seems to be intended to apply to the case where the temporary in question is created by the full-expression in the return statement, since it says the temporary will be destroyed at the end of that full-expression. Clearly that's not the case for the y+1 temporary, which will instead be destroyed at the end of the full-expression containing the call to min. Thus, I tend to think that this statement was not intended to apply to cases like that in the question. Instead, its effect, together with the other limitations on lifetime extension, is to prevent any temporary object's lifetime from being extended beyond the block scope in which it was created. But this would not prevent the y+1 temporary in the question from surviving until the end of main.



                  Thus the question remains: what is the principle that explains why the binding of ref2 to the temporary in the question doesn't extend that temporary's lifetime?



                  The wording from the current working draft that I cited earlier was introduced by the resolution of CWG 1299, which was opened in 2011 but only resolved recently (not in time for C++17). In a sense, it clarifies the intuition that the reference must bind "directly", by delineating those cases where the binding is "direct" enough for lifetime extension to occur; it is not, however, so restrictive as to only allow it when the reference binds to a prvalue. It permits lifetime extension in the S42.x case.






                  share|improve this answer













                  I will answer the question first, and then provide some context for the answer. The current working draft contains the following wording:




                  The temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference if the glvalue to which the reference is bound was obtained through one of the following:



                  • a temporary materialization conversion ([conv.rval]),


                  • ( expression ), where expression is one of these expressions,

                  • subscripting ([expr.sub]) of an array operand, where that operand is one of these expressions,

                  • a class member access ([expr.ref]) using the . operator where the left operand is one of these expressions and the right operand designates a non-static data member of non-reference type,

                  • a pointer-to-member operation ([expr.mptr.oper]) using the .* operator where the left operand is one of these expressions and the right operand is a pointer to data member of non-reference type,

                  • a const_­cast ([expr.const.cast]), static_­cast ([expr.static.cast]), dynamic_­cast ([expr.dynamic.cast]), or reinterpret_­cast ([expr.reinterpret.cast])
                    converting, without a user-defined conversion, a glvalue operand that is one of these expressions to a glvalue that refers to the object designated by the operand, or to its complete object or a subobject thereof,

                  • a conditional expression ([expr.cond]) that is a glvalue where the second or third operand is one of these expressions, or

                  • a comma expression ([expr.comma]) that is a glvalue where the right operand is one of these expressions.



                  According to this, when a reference is bound to a glvalue returned from a function call, lifetime extension does not occur, because the glvalue was obtained from the function call, which is not one of the permitted expressions for lifetime extension.



                  The lifetime of the y+1 temporary is extended once when bound to the reference parameter b. Here, the prvalue y+1 is materialized to yield an xvalue, and the reference is bound to the result of the temporary materialization conversion; lifetime extension thus occurs. When the min function returns, however, ref2 is bound to the result of the call, and lifetime extension does not occur here. Therefore, the y+1 temporary is destroyed at the end of the definition of ref2, and ref2 becomes a dangling reference.




                  There has historically been some confusion on this topic. It is well-known that the OP's code and similar code result in a dangling reference, but the standard text, even as of C++17, did not provide an unambiguous explanation as to why.



                  It is often claimed that lifetime extension only applies when the reference binds "directly" to the temporary, but the standard has never said anything to that effect. Indeed, the standard defines what it means for a reference to "bind directly", and that definition (e.g., const std::string& s = "foo"; is an indirect reference binding) is clearly not relevant here.



                  Rakete1111 has said in a comment elsewhere on SO that lifetime extension only applies when the reference binds to a prvalue (rather than some glvalue that was obtained through a previous reference binding to that temporary object); they appear to be saying something similar here by "bound ... directly". However, there is no textual support for this theory. Indeed, code like the following has sometimes been considered to trigger lifetime extension:



                  struct S int x; ;
                  const int& r = S42.x;


                  However, in C++14, the expression S42.x became an xvalue, so if lifetime extension applies here, then it is not because the reference binds to a prvalue.



                  One might instead claim that lifetime extension only applies once, and binding any other references to the same object do not further extend its lifetime. This would explain why the OP's code creates a dangling reference, without preventing lifetime extension in the S42.x case. However, there is no statement to this effect in the standard, either.



                  StoryTeller has also said here that the reference must bind directly, but I don't know what he means by that, either. He cites standards text indicating that binding a reference to a temporary in a return statement doesn't extend its lifetime. However, that statement seems to be intended to apply to the case where the temporary in question is created by the full-expression in the return statement, since it says the temporary will be destroyed at the end of that full-expression. Clearly that's not the case for the y+1 temporary, which will instead be destroyed at the end of the full-expression containing the call to min. Thus, I tend to think that this statement was not intended to apply to cases like that in the question. Instead, its effect, together with the other limitations on lifetime extension, is to prevent any temporary object's lifetime from being extended beyond the block scope in which it was created. But this would not prevent the y+1 temporary in the question from surviving until the end of main.



                  Thus the question remains: what is the principle that explains why the binding of ref2 to the temporary in the question doesn't extend that temporary's lifetime?



                  The wording from the current working draft that I cited earlier was introduced by the resolution of CWG 1299, which was opened in 2011 but only resolved recently (not in time for C++17). In a sense, it clarifies the intuition that the reference must bind "directly", by delineating those cases where the binding is "direct" enough for lifetime extension to occur; it is not, however, so restrictive as to only allow it when the reference binds to a prvalue. It permits lifetime extension in the S42.x case.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 14 hours ago









                  BrianBrian

                  66.7k798191




                  66.7k798191



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55567962%2fwhy-doesnt-a-const-reference-extend-the-life-of-a-temporary-object-passed-via-a%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                      Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                      Tom Holland Mục lục Đầu đời và giáo dục | Sự nghiệp | Cuộc sống cá nhân | Phim tham gia | Giải thưởng và đề cử | Chú thích | Liên kết ngoài | Trình đơn chuyển hướngProfile“Person Details for Thomas Stanley Holland, "England and Wales Birth Registration Index, 1837-2008" — FamilySearch.org”"Meet Tom Holland... the 16-year-old star of The Impossible""Schoolboy actor Tom Holland finds himself in Oscar contention for role in tsunami drama"“Naomi Watts on the Prince William and Harry's reaction to her film about the late Princess Diana”lưu trữ"Holland and Pflueger Are West End's Two New 'Billy Elliots'""I'm so envious of my son, the movie star! British writer Dominic Holland's spent 20 years trying to crack Hollywood - but he's been beaten to it by a very unlikely rival"“Richard and Margaret Povey of Jersey, Channel Islands, UK: Information about Thomas Stanley Holland”"Tom Holland to play Billy Elliot""New Billy Elliot leaving the garage"Billy Elliot the Musical - Tom Holland - Billy"A Tale of four Billys: Tom Holland""The Feel Good Factor""Thames Christian College schoolboys join Myleene Klass for The Feelgood Factor""Government launches £600,000 arts bursaries pilot""BILLY's Chapman, Holland, Gardner & Jackson-Keen Visit Prime Minister""Elton John 'blown away' by Billy Elliot fifth birthday" (video with John's interview and fragments of Holland's performance)"First News interviews Arrietty's Tom Holland"“33rd Critics' Circle Film Awards winners”“National Board of Review Current Awards”Bản gốc"Ron Howard Whaling Tale 'In The Heart Of The Sea' Casts Tom Holland"“'Spider-Man' Finds Tom Holland to Star as New Web-Slinger”lưu trữ“Captain America: Civil War (2016)”“Film Review: ‘Captain America: Civil War’”lưu trữ“‘Captain America: Civil War’ review: Choose your own avenger”lưu trữ“The Lost City of Z reviews”“Sony Pictures and Marvel Studios Find Their 'Spider-Man' Star and Director”“‘Mary Magdalene’, ‘Current War’ & ‘Wind River’ Get 2017 Release Dates From Weinstein”“Lionsgate Unleashing Daisy Ridley & Tom Holland Starrer ‘Chaos Walking’ In Cannes”“PTA's 'Master' Leads Chicago Film Critics Nominations, UPDATED: Houston and Indiana Critics Nominations”“Nominaciones Goya 2013 Telecinco Cinema – ENG”“Jameson Empire Film Awards: Martin Freeman wins best actor for performance in The Hobbit”“34th Annual Young Artist Awards”Bản gốc“Teen Choice Awards 2016—Captain America: Civil War Leads Second Wave of Nominations”“BAFTA Film Award Nominations: ‘La La Land’ Leads Race”“Saturn Awards Nominations 2017: 'Rogue One,' 'Walking Dead' Lead”Tom HollandTom HollandTom HollandTom Hollandmedia.gettyimages.comWorldCat Identities300279794no20130442900000 0004 0355 42791085670554170004732cb16706349t(data)XX5557367