Virtual inheritance to get storage alignment
When someone asked a question about how to solve the problem that in a class
hierarchy some classes need a stricter alignment than others, and how to
write operator new in those cases, i came up with this solution using
virtual inheritance and the dominance rule:
// provides operators for any alignment >= 4 bytes
template<int Alignment>
struct DeAllocator;
template<int Alignment>
struct DeAllocator : virtual DeAllocator<Alignment/2> {
void *operator new(size_t s) throw (std::bad_alloc) {
std::cerr << "alignment: " << Alignment << "\n";
return ::operator new(s);
}
void operator delete(void *p) {
::operator delete(p);
}
};
template<>
struct DeAllocator<2> { };
// ........... Test .............
// different classes needing different alignments
struct Interface { };
struct A : Interface, virtual DeAllocator<16> { };
struct ASpecial : A, virtual DeAllocator<4> { };
struct B : Interface, virtual DeAllocator<8> { };
int main() {
delete new A; // alignment: 16
delete new ASpecial; // alignment: 16
delete new B; // alignment: 8
}
What do you think of it? Is it a known idiom? Is it useful, or is the way
it's done wrong?
What worries me is how the size of these objects grow up from 1 byte to 4 or
8 bytes on GCC, just because we use virtual inheritance. But i think if we
already use virtual functions, the growth in size isn't too bad.
SO link to the question:
http://stackoverflow.com/questions/2366879/operator-new-overloading-and-
alignment
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]