In the Game of Thrones season 2 episode 9, Battle of the Blackwater, Ser Ilyn Payne was in the women's room acting as a bodyguard. Though the Queen claims Ser Ilyn was present to protect them and to deal with potential betrayers, she later admitted to Sansa that Ilyn's true purpose was to execute her and Sansa, and possibly the rest of the ladies who would have taken refuge in the holdfast, should Stannis Baratheon take the city.

2 Answers
2

So that they can die with honor. It wasn't uncommon for victorious besiegers to rape and pillage once they were inside the walls.

“If the city falls, these fine women should be in for a bit of a
rape.” – Cersei

Cersei should know. Her father's men did no less when they sacked King's Landing back when the Targaryens held the city.

Why didn't he stop Cersei or Sansa when they went out of the room?

But they didn't leave Maegor's Holdfast, which is a very strong fortress within the bigger Red Keep, with the only access being a heavily defended drawbridge. The guests could leave the room if they so wish (many did to go pray), but they were barred from leaving the fortress. Even if the outer walls fell, Maegor's Holdfast could still stand for a while. It was when this fortress fell that Ilyn Payne was supposed to dispense with his grisly task.

In case the battle was lost and the city captured, there was a high chance that the women would be raped by the attackers. Ser Ilyn Pane was there to kill them before this could happen, to spare them this destiny. Of course they could've killed themselves in theory, but it is very unlikely that they would go through with it, so he was there to take care of it instead, because he would be less hesitant about it.

Why didn't he stop Cersei or Sansa when they went out of the room?

Well, it was the Queen and she was not in imminent danger, so he probably had not much choice in the matter. If he had stopped her by force he could've gotten into trouble and he likely did not want to take this risk. And he probably was not looking forward to killing them as well.

Remember what happened to the targaryen children when kings landing was sacked? There is a tradition of applying terrible fates to the survivors of a fallen monarchy: the Lannisters know this better than most.
– John Smith OptionalApr 10 '14 at 21:25

Although it is diffeerent in case of Stannis, he will not allow such things but you never know about army men.
– PantherApr 19 '15 at 6:26