In truth, the sword, knife, or spear is far more dangerous than any handgun in a close in fight. Far quicker, far more damaging, and far more accurate in a real fight. The ONLY advantage the handgun, or for the most part any firearm, has is distance. That's it. It is inferior in every way to the melee weapon save for the fact it can hit things at a distance.
The flintlock only became the standard weapon of the infantry when the bayonet was invented and implemented, turning a musket into a spear. Contrary to what most people think, the vast majority of musket fighting was done hand to hand, bayonet to bayonet, breaking skulls with musket butts. Officers still carried swords, and used them to great effect in combat. While some who believe certain myths about warfare at the time, and those who have been around the era of modern fast shooting firearms retroactively believe, that "colored uniforms and standing in lines iz stoopid", such lines and formations were more effective than individuals sniping off men by themselves, as the true battle was eventually violent close up combat, not trading shots with the enemy.
Only when rifling became common to average weapons instead of specialty rifles, and the advent of the cartridge over the muzzleloader, was the effect of firepower to end the era of hand to hand combat as the means of fighting war. Only when a very fast rate of high accuracy long range fire could be produced, was the era of the bayonet's supremacy on the battlefield ended. Even then, go ahead and ask some Korean War vets about their fighting, and they might tell you that hand to hand didn't quite come to an end in 1914.
A great deal of the gun's supremacy over the melee weapon is real, in the fact that I can shoot a man with a knife at 300 yards with a .30-06 without much trouble, hopefully, before he can get even nearly close to me. The other part is heavily myth, much of it based on the concept that it is the weapon, not the man, who fights, and who wins. The man makes the weapon; the weapon does not make the man. Also is the arrogance and swagger of the man who believes that his gun makes him supreme, as well as the man who wants to believe that carrying a gun makes him immune to the knife or the fist, gives him an insurmountable advantage.
Many people are unaware. But there are also those too, who, mouth breathing and slack jawed, will not accept the fact that a gun can possibly lose to any knife or fist. The pistol is not a magic guardian against evil, or some sort of talisman, it is a weapon. And you have to win the fight.