On 27 Feb, 22:59, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
> Chris Thomasson wrote:
> > I am thinking about using this technique for all the "local" memory
> > pools in a paticular multi-threaded allocator algorithm I invented.
> > Some more info on that can be found here:
>
> >http://groups.google.com/group/comp....ead/24c40d42a0...
>
> > Anyway, here is the code snippet:
>
> > #include <cstdio>
> > #include <cstddef>
> > #include <new>
>
> > template<size_t T_sz>
> > class lmem {
> > unsigned char m_buf[T_sz];
> > public:
> > void* loadptr() {
> > return m_buf;
> > }
> > };
>
> > class foo {
> > public:
> > foo() { printf("(%p)foo::~foo()", (void*)this); }
>
> The string seems to be incorrect.
>
> > ~foo() { printf("(%p)foo::~foo()", (void*)this); }
> > };
>
> > int main(void) {
> > foo *f;
> > lmem<sizeof(*f)> foomem;
> > f = new (foomem.loadptr()) foo;
>
> It's not "incorrect", but I believe you may have a problem
> with alignment. Only a memory block sized 'sizeof(foo)'
> obtained from free store is aligned correctly to have a 'foo'
> constructed in it like that.
>
IMO, because the array is wrapped in a class there shouldnt be a
problem. IOW thc class alignment will take care of the issue. However
It should be possible to check . (Not absolutely sure if this is the
correct solution but whatever ...
regards
Andy Little
#include <stdexcept>
// aka std::tr1::
template <typename T>
struct alignment_of{
#if defined _MSC_VER
static const unsigned int value = __alignof(T);
#elif defined __GNUC__
static const unsigned int value = __alignof__(T);
#else
#error need to define system dependent align_of
#endif
};
template<typename T, size_t T_sz>
class lmem {
unsigned char m_buf[T_sz];
public:
void* loadptr() {
// check its aligned correctly
ptrdiff_t dummy = m_buf - static_cast<char*>(0);
ptrdiff_t offset = dummy % alignment_of<T>::value;
if(!offset)
return m_buf;
throw std::logic_error("lmem memory doesnt satisfy alignment");
}
};
int main()
{
typedef double type;
lmem<type,sizeof(type)> x;
}