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 33,196 of 33,346   
   Kamil Rojewski to All   
   Template setters   
   07 Sep 13 05:00:59   
   
   From: kamil.rojewski@googlemail.com   
      
   { Reformatted; please limit your lines to 70 characters -mod }   
      
   Hi,   
      
   Recently I was wondering about trying out a new approach to writing   
   setters in classes. Traditional pre-C++11 approach relied on passing   
   const & for complex types and value for simple ones, like int. That   
   didn't sit well with me, because:   
      
   1. It doesn't take advantage of modern C++11 features, like move   
       semantics.   
   2. Introduces inconsistency.   
      
   So I began to wonder about passing universal references (as per Scott   
   Meyers' terminology) instead. With this approach all setters would   
   take the form of:   
      
   template   
   void setWidget(T &&widget)   
   {   
        mWidget = std::forward(widget);   
   }   
      
   This has some pros and cons:   
      
   + Takes into account move semantics.   
   + Allows utilization of any form of operator =.   
   + Retains consistency across all types (const & vs. value arguments).   
      
   - Breaks encapsulation, as the definition needs to be visible.   
   - Moves possible type mismatch errors inside the setter, instead of   
      invocation.   
   - Can lead to confusion, as the setter becomes a type sink (although   
      the argument can be ruled out, since it propagates to operator =   
      overloads).   
      
   In my opinion the advantages outweigh the disadvantages, although   
   moving the point of possible error is a strong one. That's why I'm yet   
   to decide if I should make this my standard practice. Any thoughts?   
      
      
   --   
         [ 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