The most basic principle for gain and loss when sailing upwind is that boats closer to the new wind direction will gain (no matter which tack they're on). What's the reason for this? Remember that, when you're sailing upwind, boats on the higher ladder rungs are ahead. If the wind shifts, it also shifts all the rungs; the result is that boats closest to the shift end up on the highest ladder rungs.
In the example shown, it's clear that when the wind shifts to the right, R gains because she moves to a higher ladder rung. A less-obvious gain is made by Boat B in the same shift. Even though A has planted herself directly to windward of B, B will gain slightly on a shift in either direction. And the farther behind B is, the more distance she will gain!