c++ - How to declare an accessor to a member? -


in of classes accessors declared getname1 , in others getname2. usage perspective, looks identical. there performance benefit of 1 on other in decent compiler? there cases should use 1 of two?

class myclass {   public:     myclass(const string& name_):_name(name_)   {   }     string getname1() const     {       return _name;     }     const string& getname2() const     {       return _name;     }   private:     string _name; };  int main() {   myclass c("bala");   string s1 = c.getname1();   const string& s2 = c.getname1();   string s3 = c.getname2();   const string& s4 = c.getname2();   return 0; } 

returning reference potentially faster, because no copy needs made (although in many circumstances return-value optimization applies.

however, increases coupling. consider happens if want change internal implementation of class store name in different way (i.e. no longer in string). there no longer return reference, need change public interface, means client code need recompiled.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -