A blog I came across at http://developer-resource.blogspot.com.au/2009/01/pros-and-cons-of-returing-references.html writes:
After working in this code base for a while now I believe that
returning references are evil and should be treated just like
returning a pointer, which is avoid it.For example the problem that arose that took a week to debug was the
following:
class Foo {
std::vector< Bar > m_vec;
public:
void insert(Bar& b) { m_vec.push_back(b); }
Bar const& getById(int id) { return m_vec[id]; }
}
The problem in this example is clients are calling and getting
references that are stored in the vector. Now what happens after
clients insert a bunch of new elements? The vector needs to resize
internally and guess what happens to all those references? That’s
right there invalid. This caused a very hard to find bug that was
simply fixed by removing the &.
I can’t see anything wrong with the code. Am I misunderstanding return by reference & STL containers, or is the post incorrect?
Say for example you have 2 elements in the vector:
aandb. You return references for theser1andr2.Now another client does an insert into the vector. Since the vector has only two element storage present. It reallocs the storage. It copies
aandband insertscafter them. This changes the locations ofaandb. So referencesr1andr2are now invalid and are pointing to junk locations.If the getById method was not return by reference a copy would have been made and everything would have worked fine.