Question: 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!

Answer: 
You can't change which container a reference refers to after initialisation, but you can use the flag to control which one it is initialised to. If you want the lSwitch flag to control which container you refer to you can do so like this:

```
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 = iSwitch ? ioGaugeStats : ioCounterStats;

   // Do something with lStats
}

```

This makes lStats a reference to the same container as ioGaugeStats if iSwitch is true, and a reference to ioCounterStats if it is false.
Yes, it is completely valid. However, as you noted, it doesn't always do what you expected. Primary: REFERENCES ARE NOT POINTERS. THERE IS A BIGGER DIFFERENCE THAN . vs ->.

As you noted, a pointer points to the address of an object (or null), and can be changed at any time. 

A reference, is a reference to a particular object, always. Your code recieves a reference that you call `ioCounterStats` to an object `A`, and a reference called `ioGaugeStats` to an object `B`. Then you made `lStats` refer to `A` as well. Then you said `if (iSwitch)` assign `B` to `A`, which it happily did. Once a local reference is set, it will refer to that object until it's scope ends, period. If you need to change what it refers to, then you don't want a reference, you wanted a pointer. They are quite different.