Re: Returning a reference to a local variable
On Dec 29, 10:40 pm, pauldepst...@att.net wrote:
#include <iostream>
using namespace std;
double & GetWeeklyHours()
{
double h = 46.50;
double &hours = h;
return hours;}
//---------------------------------------------------------------------------
int main()
{
double hours = GetWeeklyHours();
cout << "Weekly Hours: " << hours << endl;
return 0;
}
According to a (hopefully reliable) website, the above is correct
code.
Why is the above _not_ an example of the sin of "returning a reference
to a local variable"? What is the difference between the return-
reference-to-local problem and the above code?
It is an example of undefined behaviour. A compiler is not required to
generate a diagnostic either.
Is it accepteable? Not in a long shot.
Here, try the following and pay attention to the output and sequence
of events.
#include <iostream>
class Hours
{
double m_d;
public:
Hours() : m_d(0.0) { std::cout << "Hours()\n"; }
Hours(double d) : m_d(d) { std::cout << "Hours(double)\n"; }
~Hours() { std::cout << "~Hours()\n"; }
Hours(const Hours& copy)
{
std::cout << "Hours(const Hours& copy)\n";
m_d = copy.m_d;
}
double get() const { return m_d; }
};
Hours& GetWeeklyHours()
{
Hours h = 46.50;
std::cout << "local initialized\n";
Hours& hours = h;
std::cout << "reference set\n";
return hours;
}
//---------------------------------------------------------------------------
int main()
{
Hours hours = GetWeeklyHours(); // is a copy (1)
std::cout << "Weekly Hours: " << hours.get() << std::endl;
}
/*
Hours(double)
local initialized
reference set
~Hours() // local destroyed here
Hours(const Hours& copy) // is a copy (1) of a reference
Weekly Hours: 6.95329e-310
~Hours()
*/
The basic rule of thumb is: if a local invokes a default or
parametized ctor, not a copy, it only lives in that scope.
It doesn't matter whether you use a reference, a 'reference to const'
or a 'pointer to const', the residual garbage left over from the
destruction of the local variable can't be guarenteed. Anything can
happen.
this is fine, btw:
Hours GetWeeklyHours()
{
return Hours(46.5);
}
but this is not:
Hours const& GetWeeklyHours()
{
return Hours(46.5);
}