c++ - how can i allocate memory for a union member that haven't been initialized -
i have got union of 2 members.
union myunion { std::wstring mem1; int mem2; myunion(std::wstring in){ this->mem1 = in; } myunion(int in){ this->mem2 = in; } myunion(const myunion& in){ if(this->mem2){ this->mem2 = in.mem2; }else{ this->mem1 = in.mem1; } } }; //and make vector out of union: std::vector<myunion> unions; //but when try push_back: unions.push_back(l"a");
it breaks out run time error: 0xc0000005: access violation writing location 0xcccccccc. , when try debug program, realize mem1 have not been allocate memory. don't know why happens , want know how can fix it.
in c++, union
not natural datatype, because doesn't fit naturally whole c++ idea of constructors , destructors. when create union in c++, not call constructors of possible types, because writing on top of eachother.
so constructor
myunion(std::wstring in){ this->mem1 = in; }
will crash because this->mem1
's lifetime string has not been started. have use like, call std::string
ctor using placement new @ address. later, if change data type, have make sure remember call dtor this->mem1
before start writing different field of union, or memory leakage or corruption.
by far simpler way trying in c++ use variant type boost::variant
going handle boilerplate , details you. (union okay if using trivial types no ctors or dtors.)
typedef boost::variant<std::wstring, int> myunion; std::vector<myunion> unions; unions.push_back(l"a");
Comments
Post a Comment