What's wrong with using return const reference

S

Subhransu

Hi All,

I read in one of the links that,

- Returning by const reference exposes the internal data structure (I
understood it to some extent that the returned reference could be
assumed to be a member variable as it has to live even after the
called function returns)
- It makes the API vulnerable for BC (Binary Compatibility) break!

Can someone please explain how? Also, I had a notion that it is better
to return by const reference as it will have some performance edge.

Regards,
Subhransu
 
Z

Zeppe

Subhransu said:
Hi All,

I read in one of the links that,

- Returning by const reference exposes the internal data structure (I
understood it to some extent that the returned reference could be
assumed to be a member variable as it has to live even after the
called function returns)

well, the reference is usually to a data member variable. Anyway, if you
return a reference, you have to document and pay attention to the
reference lifetime. If you fail doing so, you can incur in bugs
difficult to spot.

Imagine as an example a "fruit basket" that contains description of
different fruits and allows you to retrieve a description:

basket.insert("apple", "an apple is a round red fruit");
string& descr = basket.findDescr("apple");
basket.clear();
std::cout << descr << std::endl; // error!

Additionally, if basket.findDescr had to return a temporary object, it
would have problem due to the need to prolong the lifetime of it after
the end of the function. For example, if there was something as

const std::string& findDescr(const std::string& fruitName) const {
if(find(begin(), end(), fruitName) == end())
return "a fruit not present in the basket."; // error!
//...
}
- It makes the API vulnerable for BC (Binary Compatibility) break!

Uhm, this is less clear to me, as I think all the pieces of a program
have to be compiled for the same target architecture.
Can someone please explain how? Also, I had a notion that it is better
to return by const reference as it will have some performance edge.

It's right that you have optimisation, but another rule of thumb is "do
NOT over-optimise", i.e., optimise when not necessary.

Best wisehs,

Zeppe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top