Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return a const reference to small class members?

I feel like this question must surely be on SO somewhere, but either I can't figure out the right search terms or it was somehow missed.

Suppose I have class that protects its members like so...

class MyClass {
   int m_value;
public:
   MyClass(int v) : m_value(v) {}
   int value() const { return m_value; }
}

I've seen sample code all over SO that instead returns a const reference to the member variable like so...

class MyClass {
   int m_value;
public:
   MyClass(int v) : m_value(v) {}
   const int& value() const { return m_value; }
// ^^^^^^^^^^
}

I understand the value of returning const in general, and the value of returning references for composite objects, but what's the value for objects smaller than the architecture's pointer size? It seems both less efficient and less safe, with no advantage I can think of.


I suppose a similar discussion could be had for the constructor in my example, but this question is focused on returned values here.

This is the SO answer that prompted me to ask this question.

like image 775
Phlucious Avatar asked May 02 '18 14:05

Phlucious


2 Answers

Why return a const reference to small class members?

Depends if you want the caller to be able to bind a reference to m_value.

MyClass myObj;
int const& keep_an_eye_on_you = myObj.value();
cout << "Was: " << keep_an_eye_on_you << endl;
myObj.doSomething(); // say this changes the value held in m_value
cout << "Now: " << keep_an_eye_on_you << endl;

If m_value is effectively immutable, then it does not matter (other than for performance concerns, which others have expressed).

If m_value can change over time, then the caller's binding will reflect the current state, as in the example above.

like image 111
Eljay Avatar answered Oct 24 '22 14:10

Eljay


Returning a const & to a type like int is probably completely pointless and possibly degrading to performance. The same thing can be said for passing const int& as a function parameter type, but that's a little more acceptable in that it does defeat unwanted type conversions at a calling site.

It's merely a poor habit that the programmer has gotten themselves into.

like image 32
Bathsheba Avatar answered Oct 24 '22 13:10

Bathsheba