Boost logo

Boost :

Subject: Re: [boost] How to create a shallow copy without calling a constructor?
From: Stefan Strasser (strasser_at_[hidden])
Date: 2010-01-02 11:14:12


Am Saturday 02 January 2010 16:42:45 schrieb vicente.botet:
> I have looked at uninitialized_copy but if I have understood it correctly,
> it calls the copy constructor. I have tried with
>
> class C {
> public:
> C* shallow_clone() {
> C* p = reinterpret_cast<C>(malloc(sizeof(C));
> if (p==0) {
> throw std::bad_alloc();
> }
> memcpy(p, this, sizeof(C));
> return p;
> }
> };
>
> But I suspect that this is not correct in general. Is this correct on some
> particular cases? if yes on witch ones? 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?

new char[sizeof(T)], reinterpret_cast and std::memcpy().
the C++ standard explicitely requires char-arrays to be aligned appropriately
for objects of any type that fits in the array.

I don't know the requirements of your cache, but there are many cases were
copying an object like this will fail. e.g. when the object contains a
boost::interprocess::offset_ptr, so this is only a portable way to copy PODs.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk