Prev: pros and cons of returning const ref to string instead of string by value
Next: pros and cons of returning const ref to string instead of string by value
From: Francis Glassborow on 8 Dec 2009 07:38 Andrew wrote: > No, you can't move from one to the other, it has to be all or nothing. > It is VERY dangerous to mix the two. Consider this: > > string get_value() const; > const string& get_something() const > { > return get_value(); > } > > This will compile but will fail at runtime. get_something is returning > a reference to a temporary. The compiler will warn but many developers > routinely ignore compiler warnings. I just got bitten by this bug in > the project I am working on. I was not proposing that. What I was intending was: std::string get_value() const {return mystring;} std::string const & get_ref() const {return mystring;} Or even: std::string get_ref const & () const {return mystring;} std::string get_value() const {return get_value;} -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |