
Am Saturday 02 January 2010 23:34:51 schrieb vicente.botet:
class base_transaction_object { public: virtual base_transaction_object* shallow_clone() const = 0; virtual void copy_state(base_transaction_object const * const) = 0; virtual void cache_deallocate()=0; virtual ~base_transaction_object() {}; ... };
The user can define a shallow copy himself as follows
class C : public base_transaction_object { C(C const& rhs, shallow_copy_t) { // do a shallow copy } public: base_transaction_object* shallow_clone() { C* p = reinterpret_cast<C>(new char[sizeof(C)]); return new (p) C(*this, shallow_copy); } void copy_state(base_transaction_object const * const rhs) { // do a shallow assignement } void cache_deallocate() { delete[] reinterpret_cast<char*>(this); } };
I want to define a generic mixin that define these function, something like:
template <class Derived, typename Base=base_transaction_object> class shallow_transaction_object : public Base { typedef Base base_type; public: base_transaction_object* shallow_clone() const { Derived* p = reinterpret_cast<Derived*>( new char[sizeof(Derived)]); std::memcpy(p, static_cast<Derived const*>(this), sizeof(Derived)); return p; }
void cache_deallocate() { delete[] reinterpret_cast<char*>(this); }
void copy_state(base_transaction_object const * const rhs) { std::memcpy(static_cast<Derived *>(this), static_cast<Derived const * const>(rhs), sizeof(Derived )); } };
So the user can just declare its own class as
class C : public shallow_transaction_object<C> { // members concerning the user space };
Can this be done in a portable way?
depends on if you really mean portable or "defined" (by C++ standard). I doubt memcpy()ing objects with a virtual pointer is defined, but I think it'll work on all implementations I know of if you always copy the most derived type. what types can class C : shallow_transaction_object contain? can it contain pointers or is it limited to "shallow types"? for the latter, you might want to make the decision if memcpy() can be used based on boost::serialization::is_bitwise_serializable. is the object in the cache used or is it only stored to be copied back to the exact same position of the original object, in case the transaction fails?