home bbs files messages ]

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 32,574 of 33,346   
   fmatthew5876 to All   
   Re: rvalue references and parameter pass   
   03 Oct 12 21:25:35   
   
   From: fmatthew5876@googlemail.com   
      
   I ran some tests which some might find interesting. It turns out the   
   best version of a matrix multiply like this is below. I found this   
   interesting because of all of the articles out there talking about the   
   merits of passing by value. In most cases pass by value and rvalue   
   reference overloads are useful when you have move constructors, but in   
   this case there is no concept of a move constructor.   
      
   Anyway the best version is this:   
   Matrix4 operator+(const Matrix4& l, const Matrix4 & l) {   
      Matrix4 m(l);   
      m+= r;   
      return m;   
   }   
      
   I tested 4 cases by replacing the copy constructor with a print   
   statement and running the following:   
      
   Matrix4 m, n, x;   
      
   x = m + n;   
      
   x = m + Matrix4();   
      
   x = Matrix4() + n;   
      
   x = Matrix4() + Matrix4();   
      
   In all 4 cases, the const reference version does 1 copy. The reason is   
   because of Return value optimization. In all cases the only copy is   
   when we do m(l); The compiler is smart enough to construct the return   
   value directly into x.   
      
   If you do this version:   
   Matrix4 operator+(Matrix4 l, const Matrix4& r) {   
      l+= r;   
      return l;   
   }   
      
   Sometimes you get 2 copies. This happens in cases 1 and 2 because   
   return value optimization does not work when you return one of the   
   function parameters. So first the lvalue is copied into l, then the   
   return value is copied again into x.   
      
   One final note, don't do this:   
      
   Matrix4 operator+(const Matrix4& l, const Matrix& r) {   
      Matrix4 m(l);   
      return m+= r;   
   }   
      
   You might think you are being clever, but what you're returning now is   
   the return value of operator+= which is a Matrix4 reference. The   
   compiler has no way of knowing what this reference points to so it   
   cannot do RVO.   
      
      
   --   
         [ 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