Forums before death by AOL, social media and spammers... "We can't have nice things"
|    comp.lang.c++.moderated    |    Moderated discussion of C++ superhackery    |    33,346 messages    |
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
|    Message 33,334 of 33,346    |
|    =?ISO-8859-1?Q?=D6=F6_Tiib?= to fran...@googlemail.com    |
|    Re: rvalue reference factory?    |
|    17 May 14 18:09:46    |
   
   From: ootiib@hot.ee   
      
   On Wednesday, 14 May 2014 16:20:02 UTC+3, fran...@googlemail.com wrote:   
   > Am Dienstag, 13. Mai 2014 21:50:02 UTC+2 schrieb Daniel Kr�gler:   
   >> Understandeably. Your code attempts to return the reference to an object   
   >> with local storage duration, which is undefined behaviour, because that   
   >> object is already destroyed after the function return. This problem is   
   >> not specific to rvalue-references but to references or pointers in   
   >> general.   
   >   
   > This hint helped me to change the code and see it (see below).   
   > I was thinking an rvalue reference variable on the stack can be   
   > used as a storage(!) target for a final std::move() of a factory   
   > function - but this was wrong.   
   > As you said: it's just a reference.   
      
   Rvalue reference is for to indicate that the object so referred is safe   
   to move from. It is still business of programmer to achieve that the   
   lifetime of object does not end before the reference is used.   
      
   It can not magically extend lifetimes of objects in local storage of   
   function, so what you did does still not work. Most already know that   
   it does not work, but some novices attempt it:   
      
    // FAIL: most compilers complain   
    Derived1* build()   
    {   
    Derived1 d;   
    return &d;   
    }   
      
   Rvalue reference is not some magic tool to make above to work. It still   
   does not work and there's no point to write:   
      
    // FAIL: the same failure   
    Derived1 && build()   
    {   
    return Derived1();   
    }   
      
   Confusion perhaps arises from unfortunate name of 'std::move'. It does   
   move nothing. 'std::move' merely obtains an rvalue reference to its   
   argument. On your case what 'Derived()' produces is already rvalue   
   reference so all that 'move' does is that it fools compiler into trusting   
   that you know what you are doing:   
      
    // FAIL: same failure, but no compiler's warnings   
    Derived1 && build()   
    {   
    return std::move(Derived1());   
    }   
      
      
   --   
    [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
    [ comp.lang.c++.moderated. First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
(c) 1994, bbs@darkrealms.ca