The reason a problem emerges is that the destructor runs whenever the memory for a class object is reclaimed:
delete
operator is
called explicitly.
In the example, the destructor runs because the memory for a railroad-car copy is reclaimed, but, unfortunately, the destructor further reclaims the memory chunk allocated for the serial number, which is shared with the original object:
<-- Retained | Reclaimed --> | | Memory reserved for | Memory reserved for r, railroad_car argument | the railroad_car parameter | | | v | v *-----* Copy | *-----* | | -------------> | | | |-----| | |-----| | | | | | |-----| | |-----| | | ---------------* *-------------- | | |-----| | | | *-----* | | | | | | *-------- | | -------* | v v | *---*---*---*---*---*---*---*---*---* | | | | | | | | | | | | *---*---*---*---*---*---*---*---*---*