Re: In-memory construction of variant types/subclasses?
Hi,
Yes, look up 'in place new' on parashift.
Here is a piece of my Variant type code:
// in the header
union {
Int8 Char;
Int64 Long;
UInt8 UChar;
UInt64 ULong;
double Double;
bool Bool;
char String [ sizeof( std::string ) ];
char Map [ sizeof( std::map<UVar*,UVar*, UFindVar> ) ];
char SRefPtr[ sizeof( MSRefPtr<ISerialize> ) ];
char WRefPtr[ sizeof( MWRefPtr<ISerialize> ) ];
char KeyStroke[ sizeof( MKey ) ];
};
And then in the implementation if the variant is for instance string: (from
a piece of the copy constructor passed variable Var)
case eString:
new( this->String ) string( *reinterpret_cast<string const *const>(
Var.String ) );
break;
--
Make sure to set the alignment options for your compiler otherwise maybe
stuff could get misaligned i.e. on char istead of four byte boundary.
Regards, Ron AF Greve
http://moonlit.xs4all.nl
"Ulrich Hobelmann" <u.hobelmann@web.de> wrote in message
news:4gq1k3F1ntqprU1@individual.net...
Hi, slowly transitioning from C to C++, I decided to remodel a
struct/union (i.e. type identifier as first field, union of variant types)
as a class + subclasses. Switching functions are replaced by virtual
functions. So far so good.
Now what I used to do is have a struct, set its type and union member, and
return a pointer. I.e. I initialized the struct appropriately and
returned a reference. Now I'd like to do that in C++ (right now I
construct a new subclass with "new" and delete it after every call,
because the instance is only needed very shortly anyway; seems ugly to
me).
I tried to define a union that contains all subclasses (that I will ever
use) of the base class, but C++ complains that it can't have objects with
constructors or destructors inside a union.
Is there any way to have a static piece of storage, and to return
references/objects(by value) or pointers to this piece of storage, while
also initializing it (i.e. myunion.objectB = ObjectB(); return
myunion.objecTB; or something like that)? In C I didn't need malloc() in
this case; I don't see why I should need new() now.