Managing the Discriminant and Destroying the string
The assignment operators will set tok
and assign the corresponding member of the union
. Like the destructor, these members must conditionally destroy the string
before assigning a new value to the union
:
Token &Token::operator=(int i){ if (tok == STR) sval.~string(); // if we have a string, free it ival = i; // assign to the appropriate member tok = INT; // update the discriminant return *this;}
If the current value in the union
is a string
, we must destroy that string
before assigning a new value to the union
. We do so by calling the string
destructor. Once we’ve cleaned up the string
member, we assign the given value to the member that ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.