How do aircraft altimeters calculate altitudes accurately while airborne?
Altimeters are calibrated to a standard atmosphere model (International Standard Atmosphere, ISA). 

What the altimeter shows you is the vertical distance between the altitude equivalent to your current pressure (pressure altitude) and a reference "pressure altitude". The reference pressure altitude is set in pressure units (hPa or In. Hg) on the altimeter subscale. This is known as the "altimeter setting", set in the "altimeter setting window".


Image credit: FAA Pilots Handbook of Aeronautical Knowledge

Flying at lower altitudes (below "transition altitude"), the altimeter is set to airport/regional QNH, which is a pressure calculated so that if you were standing on the measurement point, the altimeter would indicate your exact elevation. At other altitudes, it would approximate altitude above mean sea level, although it would show incorrectly if temperature differed from ISA.

Above transition altitude, the altimeter is set to QNE, or standard pressure (1013.25 hPa, or 29.92 In. Hg). The altimeter will now only indicate correctly if both temperature and pressure are in accordance with ISA. You are now flying on "flight level" (where the FL is your QNE indication in hundreds of feet, ie 20,000 ft = FL200).

For the purpose of avoiding obstacles, both QNH and QNE have to be corrected using various methods, which are described in various manuals. (QNH for temperature, QNE for both temperature and pressure, both for other possible factors such as wind etc). For instance, this diagram shows three different aircraft, all flying the same pressure altitude, but with three different true altitudes:

Image credit: FAA Pilots Handbook of Aeronautical Knowledge

However, altitude is also used for the purpose of traffic separation, and for this purpose, neither QNH or QNE is corrected. This might sound counter-intuitive, but as long as your altimeter is showing the same error as any conflicting traffic, you can be safely separated, therefore: The altitude shown on the altimeter is not corrected at all (except by calibration for possible aerodynamic interference, such as compressibility, venturi-effects etc).

In technically sophisticated aircraft, barometric altitude input is used for vertical navigation. Since vertical navigation is concerned with the true altitude of the aircraft, the aircrafts Air Data Computer (ADC) will calculated a true altitude based on information available to it (either through sensors, or through pilot input). The true altitude is however, as stated, not shown on the pilots primary flight instruments.