bitrex
unread,Mar 30, 2017, 9:50:07 AM3/30/17You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
Suppose I have a structure like this, where a wrapper class for a POD
struct has a static memory buffer, and on construction a copy of the POD
struct is placed in it via placement new. Then another class wraps that,
and using the CRTP ensures that each child class has its own copy of the
buffer (rather than one being shared among all the subclasses.)
And suppose I have a "constexpr" function that creates a constant vector
or array of these objects at runtime, initialized with the default
constructor. The classes inside just sit around holding their static
buffer and a nullptr.
And then I create a stack data structure holding pointers to those
objects. What I'd like to be able to do is pop a pointer off the stack,
dereference it, and assign it such that the operation constructs a new
wrapper holding my POD data "in place" in the vector/array of originally
default-initialized objects.
I was thinking "PODWrapper" could also hold a reference to the stack, so
that the destructor would push its own "this" pointer back on it when
the wrapper went out of scope.
I'm not sure the best way to write the copy constructors for the
following two classes such that dereferencing and assignment for this
type of class is possible, though, without ending up with memcpys that
try to use the same source and destination argument.
#include <cstring>
struct POD
{
int a;
int b;
int c;
};
template <template <typename> class Derived,
typename T>
struct PODHolder
{
virtual ~PODHolder() {}
operator T() const { return *pod_ptr_; }
T* operator&() const { return pod_ptr_; }
T* operator&(const PODHolder& other) const { return pod_ptr_; }
protected:
PODHolder() = default;
PODHolder(const T& pod) :
pod_ptr_(new (_pod_buf()) T(pod))
{}
PODHolder(const T* pod) : pod_ptr_(_pod_buf())
{
std::memcpy(pod_ptr_, pod, sizeof(T));
}
private:
static char* _pod_buf()
{
static auto buf = new char[sizeof(T)];
return &buf[0];
}
T *const pod_ptr_ = nullptr;
};
template <typename T>
struct PODWrapper : public PODHolder<PODWrapper, T>
{
PODWrapper() = default;
PODWrapper(const T& pod) :
PODHolder<PODWrapper,T>(pod) {}
PODWrapper(const T* pod) :
PODHolder<PODWrapper,T>(pod) {}
};