C++: Union Destructor -


a union user-defined data or class type that, @ given time, contains 1 object list of members. suppose possible candidate members needed allocated dynamically. eg.

// union destructor #include <string> using namespace std;  union person { private:     char* szname;     char* szjobtitle; public:     person() : szname (nullptr), szjobtitle (nullptr) {}     person (const string& strname, const string& strjob)     {         szname = new char[strname.size()];         strcpy (szname, strname.c_str());          szjobtitle = new char [strjob.size()];         strcpy (szjobtitle, strjob.c_str());    // obvious, both fields points @ same location i.e. szjobtitle     }     ~person()   // visual studio 2010 shows both szname , szjobtitle     {           // points same location.         if (szname) {             delete[] szname;     // program crashes here.             szname = nullptr;  // avoid deleting deleted location(!)         }         if (szjobtitle)             delete[] szjobtitle;     } };  int main() {     person ("your_name", "your_jobtitle");     return 0; } 

above program crashed @ 1st delete statement in ~person (at moment when szname contains valid memory location, why?).

what correct implementation destructor?

same way, how destruct class object, if class contains union member (how wrtie destructor class including union)?

you can use 1 member of union @ time because share same memory. in constructor, however, initialize both members, overwrites each other, , in destructor end releasing 2 times. you're trying use if struct (based on names of fields need use struct).

nevertheless, if need union need struct kind of envelope has id representing member being used, constructor , destructor handles resources.

also - arrays small. size() returns number of characters, if use char* string type need space null-character (\0) handle termination.

if need unions, try using boost.variant. lot easier use normal unions.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -