Re: How to create a shallow copy without calling a constructor?
viboes wrote:
I need to create a cache of a transactional object without using the
new operator nor the copy constructor of the class. This cache needs
only to copy the raw memory of the copied instance, is for that I have
called it shallow_clone
If you just want to copy the memory of an object, use this:
vector<char> m(sizeof o);
memcpy(&m[0], &o, sizeof o);
However, just having this memory is useless when it contains any pointers to
external storage or internal storage. With that in mind, I wonder where your
requirement to only copy the raw memory comes from.
The following will create a deep copy and don't respect my
requirements
class C {
public:
C* shallow_clone() {
return new C(*this);
}
};
If C actually is a POD, this boils down to a simple memcpy(). If C is not a
POD, a memcpy() wouldn't work, as mentioned above. So, you don't gain
anything from not doing it this way - unless of course there is some problem
to solve that you didn't explain here.
Note: It's sometimes better to ask for a solution to a problem than to ask
how to implement a very specific solution to that problem!
C* shallow_clone() {
C* p = reinterpret_cast<C>(new char[sizeof(C)]);
if (p==0) {
throw std::bad_alloc();
}
std::memcpy(p, this, sizeof(C));
return p;
}
The returned memory is not a C instance, so it shouldn't be a pointer to C!
I would rather return some handle to the memory and create a similar
function to restore the internal state from this memory, but this isn't
good.
But I suspect that this is not correct in general. Is this correct on
some particular cases? if yes on witch ones?
Apart from the unnecessary use of reinterpret_cast, the idea seems to be the
same as with the use of std::vector above.
Is there a way to create such a cache instance without calling to the
constructor in a portable way using some low level C++ interface?
Yes. How to do that depends on what exactly you are trying to achieve, which
isn't clear yet.
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]