The formation of counterrotating cores in elliptical galaxies