-
memcpy()
Code:
AnyClass *s1 = (AnyClass *) malloc(sizeof(AnyClass));
AnyClass *s2 = (AnyClass *) malloc(sizeof(AnyClass));
Now if I use something like this, where AnyClass contains any pointer variable in its private section, will this work??? or how this can be achieved???
(after some work with the object *s2)
Code:
memcpy( (AnyClass *) s1, (AnyClass *) s2, sizeof(AnyClass) );
-
Depends what you mean by "work".
One problem with;
Code:
AnyClass *s1 = (AnyClass *) malloc(sizeof(AnyClass));
is that no constructor of class AnyClass is invoked. In practice, with most compilers, the virtual function table for the object will be uninitialised, so any attempt to call a virtual member function will yield unpredictable behaviour.
The code;
Code:
memcpy( (AnyClass *) s1, (AnyClass *) s2, sizeof(AnyClass) );
I suspect (but haven't checked) that this will yield undefined behaviour if AnyClass is not a POD type (i.e. it is not a type that makes sense to a C compiler). At best, the results are poorly defined as the intent is that a programmer will not use memcpy() to copy C++ objects (which may have constructors, destructors, and other member functions).
Instead of trying to use memcpy() like this, make use of the copy constructor and assignment operator for the class. There may be either supplied by the compiler or written by hand (to do things that the compiler-supplied versions do not). The only exception to this statement would be instances where the class designer has deliberately suppressed copy constructor and assignment operator --- and memcpy() is not a valid workaround for that.
-
In general, no it won't work except in very limited cases.
Why do you ask, is there a reason you feel you need this kind of code?
-
> AnyClass *s1 = (AnyClass *) malloc(sizeof(AnyClass));
Use new / delete not malloc, so that
a) constructors and destructors get called
b) you don't need icky castarama to get it to compile.
> memcpy( (AnyClass *) s1, (AnyClass *) s2, sizeof(AnyClass) );
If your class has a properly written copy constructor, then
*s1 = *s2;
will do the right thing all the time, even if it's non-POD.
If this is in relation to your other C++ thread about rolling your own list, I'd say you need to go learn some C++ first.
Cos at the moment, it looks like C munged into C++.