I wish to seek a bit of feedback (to help me see if my position on the issue is correct or not) regarding returning by const reference vs. returning by value (for performance reasons).
To elaborate:
#include "BigDataStruct.h"
class DataGiver
{
public:
BigDataStruct getByValue() const { return myData; };
const BigDataStruct& getByConstRef() const { return myData; };
private:
BigDataStruct myData;
}
My gut feeling says there may (or may not) be a slight performance increase for getByConstRef()
over getByValue()
in situations like:
const BigDataStruct& someData = someDataGiver.getByConstRef();
but there won't be (hardly) any for calls like:
BigDataStruct someData = someDataGiver.getByConstRef();
Also - which gives me some discomfort - is that in the first scenario someData is tied to actual member in someDataGiver, in the sense that if the member there changes someData also changes and if someDataGiver expires/dies someData becomes... undefined?
As such I try to discourage my coworkers from returning by const reference (unless we actually WANT a reference to the object for other reasons - e.g. in singleton factories). Do I have a point here or am I merely nitpicking and annoying my coworkers for no good reason?
(I am aware of the rule of thumb for optimization: 1) Don't do it 2) Don't do it yet - and use a profiler before actually doing it)