The 33-year-old seized the pink jersey with a powerful performance in Saturday's penultimate stage and finished Sunday's ceremonial 126-km flat route unscathed as Cavendish produced a vintage performance to win his last-ever Giro stage.
Cavendish, who will retire at the end of the season, marked his final appearance at the Giro with a sensational sprint victory, clinching his first victory for Astana Qazaqstan and a 17th career win at the Giro.
Jumbo Visma-rider Roglic finished 14 seconds ahead of Thomas (Ineos Grenadiers) and 75 seconds ahead of Joao Almeida of UAE Team Emirates in the overall standings to add a first Giro title to his three Vuelta triumphs from 2019 to 2021.
In 2020, Jumbo-Visma rider Roglic lost the 2020 Tour de France title after giving up his lead and the overall race victory to compatriot Tadej Pogacar in a mountain time trial on the penultimate stage.
It appeared as if Roglic's title hopes were evaporating again when he rode over a pothole around midway through Saturday's brutal climb up Monte Lussari and his chain came off, before losing more time as he was forced to change bikes.
But, cheered on by thousands of fans from across the border to Slovenia, he regrouped to take a 14-second overall advantage and made no mistake in the final stage, cruising through the Italian capital to expand his Grand Tour portfolio.