I have the following code:
void cStatisticDBSerializer::GetStats (std::map <std::string, long long >& ioCounterStats,
std::map <std::string, long long >& ioGaugeStats,
bool iSwitch)
{
// Before getting the stats, clear the containers
ioCounterStats.clear ();
ioGaugeStats.clear ();
std::map <std::string, long long >& lStats = ioCounterStats;
if (iSwitch)
{
lStats = ioGaugeStats;
}
// Do something with lStats
}
The question is: Is it valid to assign the function input reference to the local variable lStats? For some reason, this compiles fine, but does not behave as expected. However, if I change lStats to a pointer and assign it as follows (e.g.):
std::map <std::string, long long >* lpStats = &ioCounterStats;
It works just fine.
Could somebody please explain what’s going on here. Thanks!
You can’t reassign a reference once it has been created. Instead every use of it will “refer” to the original assignment. Your first example is equivalent to: