Does return by const reference make sense?
Hello all!
Please look at this code:
class X
{
public:
bool f () const {return true;}
};
class Y
{
public:
X get () const {return x;}
const X& get_ref () const {return x;}
private:
X x;
};
Y y;
if (y.get().f()) do_something ();
if (y.get_ref().f()) do_something ();
I believe that modern compilers should optimize "get" method and avoid
creation of temporary object if there are no side effects in copy
constructor.
In result "y.get().f()" and "y.get_ref().f()" will have the same cost.
Please correct me if I'm wrong here.
What makes me think so?
Return value optimization already makes our code not to depend on
number of copy constructor invocations.
And it works even if copy constructor has side effects.
So I just does not see the reason not to do such optimization.
Returning by reference can introduce some major design problems
especially if you do it in base class.
For example:
class Base
{
public:
virtual const std::string& get () const = 0;
};
class DerivedDetails
{
public:
std::string get () const {return m_string;}
private:
std::string m_string;
};
class Derived: public Base
{
public:
virtual const std::string& get () const
{
return m_details.get(); // Ups! Segfault here. Return a
reference to temporary object.
};
private:
DerivedDetails m_details;
};
This kind of error is very simple to make and very hard to find
(without compiler's help).
There are too possible fixes:
1. You can make the DerivedDetails::get to return a reference too.
* It is not always possible. For example it is a library class.
* It can just move the problem one level deeper.
2. You can store local copy of string in Derived class.
* It is ugly.
* It has even higher cost than return by value if I was right about
optimization.
So I have a strong belief that return by reference in base class is
*very bad* style.
All of this makes me think that return by const reference does not
make the sense at least if there are no side effects in copy
constructor.
And it's better in most cases to return T or const T.
Please write what you think about it.
Thanks,
Igor
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]