Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - const members / return const int& vs return int

Tags:

c++

What do we mean by those C++ lines? Are there alternative ways to writing them?

const int& a() const;
int getA() const;

Thanks.

like image 788
Simplicity Avatar asked Mar 31 '11 07:03

Simplicity


1 Answers

These two are two possible signatures for a member function in a class that promises not to change the object itself. In the first case it will return a constant reference to an integer (possibly a member attribute), the reference being const means that the caller will not be able to use it to change the internal attribute. The second case it returns an integer by value.

There are slight differences in the semantics, but in most cases they will not be important, consider them as two functions to obtain a value. For a case where it will make a difference see this:

class test {
public:
   test() : m_value() {
      std::cout << &m_value << std::endl; // print where the attribute is
   }
   int const & getValue() const {
      return m_value;
   }
   int copyValue() const {
      return m_value;
   }
   void setValue( int value ) {
      m_value = value;
   }
private:
   int m_value;
};
int main() {
   test t;                      // will printout an address [1]
   int v1 = t.getValue();       // caller copies the value
   int v2 = t.copyValue();      // caller copies the value (itself a copy in hte calle)
   int const &r = t.getValue(); // reference to t.m_value
   int const &c = t.copyValue();// reference to *copy* [2]
   std::cout << v1 << v2 << r << c
      << std::cout;             // 0000
   std::cout << &v1 << &v2      // 4 pointers, the third is [1] a r *is* t.m_value
      << &r << &c << std::cout; //     the rest should be different
   t.setValue( 5 );
   std::cout << v1 << v2 << r   // 0050, v1 and v2 where copies, r *is* t.m_value
      << c << std::cout;
}

The line marked with [2] uses a strange feature of the language by which if you obtain a constant reference to an r-value (temporary) the compiler will bind that temporary to the reference and keep it alive until the reference goes out of scope (basically it turns the r-value temporary into a hidden variable and binds the reference to it).

I added that line to be explicit in that the difference in behavior is not due to the receiving end main making a copy of maintaining a reference, but rather (also to be precise) by the signature of the accessor.

like image 149
David Rodríguez - dribeas Avatar answered Nov 19 '22 20:11

David Rodríguez - dribeas