Son of a bitch I need coffee! Man, I accidentally posted another wrong
version.
http://appcore.home.comcast.net/vzoo...oc/example.cpp
(right one this time!)
So sorry for any inconveniences/confusions... BTW, could you please "try" to
not flame me "too" bad!
:^(...
example.cpp
______________
// sample program
#include <new>
#include <cstddef>
#include <cassert>
#include <cstdio>
// aligns a ptr from a raw ptr
static void* alignptrraw(
void const *ptr,
size_t const offset,
ptrdiff_t const sz) {
ptrdiff_t const base = reinterpret_cast<ptrdiff_t>(ptr) + offset;
ptrdiff_t const align = (base + sz - 1) & -sz;
if (align % sz || align < base) {
assert(! (align % sz));
return 0;
}
return reinterpret_cast<void*>(align);
}
// get the size of an align
template<typename T>
static size_t alignsztype(size_t offset) {
return ((sizeof(T) * 2) - 1) + offset;
}
// aligns a type ptr from a raw ptr
template<typename T>
static void* alignptrtype(
void const *ptr,
size_t const maxsz,
size_t offset,
ptrdiff_t sz = sizeof(T)) {
if (alignsztype<T>(offset) >= maxsz) {
assert(alignsztype<T>(offset) < maxsz);
return 0;
}
return alignptrraw(ptr, offset, sz);
}
// autoptr_dtor class
template<typename T>
class autoptr_dtor {
T * const m_ptr;
public:
autoptr_dtor(T * const ptr) : m_ptr(ptr) {}
~autoptr_dtor() {
if (m_ptr) { m_ptr->~T(); }
}
};
// foo class
class foo {
int m_myint;
public:
foo(int my) : m_myint(my) {
printf(" (%p)- foo::foo(int my=(%d))- myint(%d)\n",
(void*)this, my, m_myint);
}
~foo() {
printf(" (%p)- foo::~foo()- myint(%d)\n",
(void*)this, m_myint);
}
};
// prompt util
static char prompt_getchar(char const*);
#define prompt_exit(vzmp_buf)\
((int)prompt_getchar((vzmp_buf)))
#define BASEBUF_SZ() 4096
#define L2_CACHELINE_SZ() 64
// entry
int main(void) {
{
// setup base buffer and offset
size_t offset = 0;
unsigned char buf_base[BASEBUF_SZ() + L2_CACHELINE_SZ() - 1] = {0};
// setup l2-cacheline aligned buffer
void* const buf_l2cache = alignptrraw(buf_base, 0, L2_CACHELINE_SZ());
printf("%p - %p\n", (void*)buf_base, (void*)buf_l2cache);
// setup base foo buffer
foo* const buf_foo = static_cast<foo*
const>(alignptrtype<foo>(buf_l2cache, BASEBUF_SZ(), 0));
// acquire a ptr, and bump the offset
autoptr_dtor<foofp1(new (buf_foo + offset) foo(1));
offset++;
// acquire a ptr, and bump the offset
autoptr_dtor<foofp2(new (buf_foo + offset) foo(2));
offset++;
// acquire a ptr, and bump the offset
autoptr_dtor<foofp3(new (buf_foo + offset) foo(3));
offset++;
// acquire a ptr, and bump the offset
autoptr_dtor<foofp4(new (buf_foo + offset) foo(4));
offset++;
} return prompt_exit("\n\n--- press <ENTERto exit ---\n");
}
// prompt util
char prompt_getchar(char const *buf) {
printf("%s", buf);
return getchar();
}
_____________