Re: returning references
On Jan 3, 7:26 pm, pauldepst...@att.net wrote:
Below is posted from a link for Stanford students in computer
science.
QUOTE BEGINS HERE
Because of the risk of misuse, some experts recommend never returning
a
reference from a function or method.
QUOTE ENDS HERE
I have never heard anyone else say that it is a problem for a function
to return a reference. Are there really experts who object, or is
this nothing other than the commonplace observation that reference-
returning is a somewhat difficult concept that needs to be learned
carefully? (I am just learning about this now.) Assuming programmers
have some degree of competence and are able to avoid returning
references to locals and so on, what (if anything) are the pitfalls?
Paul Epstein
Nothing wrong in returning references, example: various operators.
You already coverred the case of returning a temporary.
One pitfall is side-effects where an accessor might _get_ nasty.
Thats where CV-qualifiers play an important role.
#include <iostream>
#include <ostream>
class N
{
int m_n;
public:
N(int n) : m_n(n) { }
// accessors
int& getnasty() { return m_n; } // nasty
int const& getsafe() const { return m_n; }
void set(const int& n) { m_n = n; }
// friend op<<
friend std::ostream&
operator<<(std::ostream& os, const N& r)
{
return os << r.m_n;
}
};
int main()
{
N instance(9);
std::cout << instance << std::endl;
instance.getnasty() = -1; // nasty side-effect
std::cout << instance << std::endl;
instance.set(8);
std::cout << instance << std::endl;
std::cout << instance.getsafe() << std::endl;
}
/*
9
-1
8
8
*/