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.