local scope and references

In the below example, we instantiate a thermo object and we pass it as an argument to set_thermo. Now the fact that I passed that object by reference, does that mean when this function exits, since thermo was declared in this scope, that the reference will be deleted? If I pass thermo by value rather than reference, when this function exits, will thermo still exist as an attribute of report?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ReportList ReportParser::readReports(Msg & data)
{
	ReportList reports;
	Report report;
	THermo thermo;

	report.set_unit_id(readBytes(data, &idx));

	int fuel_level = (int)readBytes(data, &idx);
	thermo.set_fuel_level(fuel_level);

	report.set_thermo(&thermo);
	reports.append(report);
	return reports;
}
It depends on what set_thermo does with the pointer.

How it works is...

1) your 'thermo' object will be destroyed when readReports exits.

2) Any pointers that pointed to 'thermo' become bad pointer in that they point to an object which no longer exists.

3) Attempting to dereference a bad pointer is... well.. bad. Potential program crash... or it might just make your program act very strange.


So yeah... if ReportList::set_thermo records that pointer and tries to access it later... then that's a problem. But if it only uses the pointer within the set_thermo function itself, it'll be okay.
WHat if I use this instead:

report.set_thermo(&thermo);

With this definition:

1
2
3
4
5
6
7
8
9
10
class Report
{
public:
...
void    set_thermo(THermo thermo)	{ m_thermo = thermo; }
Thermo thermo()                              { return m_thermo;}
private:
...
THermo  m_thermo;
};


I need to later access it like this:

1
2
Thermo thermo = report.get_thermo
int fuel_level = thermo.fuel_level()
WHat if I use this instead:
[snip]
With this definition:


That definition would create a copy... so you'd be safe. This is what I'd recommend.

Your Report class would then have its own THermo object and would not need to refer to an outside object. So when the local 'thermo' object in readReports goes out of scope and dies... you have no problem because Report wouldn't be using it any more.



Although if you change the function to pass by value... then this:
report.set_thermo(&thermo);
won't work because you're passing it a pointer. You'd have to remove the & in this case.
Topic archived. No new replies allowed.