Debug help - Programming in D, page 670 allocate buffer of 10 MyClass class instances
Ali Çehreli
acehreli at yahoo.com
Wed Sep 3 20:34:59 UTC 2025
On 9/3/25 5:10 AM, Brother Bill wrote:
> Made some further changes, and have additional questions.
One of your question involves object aligment, which I mention here:
https://ddili.org/ders/d.en/memory.html#ix_memory..alignof
I discovered two (somewhat cryptic) functions there that computes sizes
of objectn with padding:
T * nextAlignedAddress(T)(T * candidateAddr) {
import std.traits;
static if (is (T == class)) {
const alignment = classInstanceAlignment!T;
} else {
const alignment = T.alignof;
}
const result = (cast(size_t)candidateAddr + alignment - 1)
/ alignment * alignment;
return cast(T*)result;
}
size_t sizeWithPadding(T)() {
static if (is (T == class)) {
const candidateAddr = __traits(classInstanceSize, T);
} else {
const candidateAddr = T.sizeof;
}
return cast(size_t)nextAlignedAddress(cast(T*)candidateAddr);
}
> // ensure myClassSize is divisible by 8, to allow for padding
So, instead of the hard-coded 8, I think the sizeWithPadding() function
template above should be helpful here.
> Questions:
> 1. Is it necessary to pad myPaddedClassSize to an 8 byte granularity on
> 64 bit machine?
Yes but you we use the .alignof property instead of relying on a
constant like 8.
> If so, should emplace() be modified to provide the padding
internally?
I feel like it's too much freedom for a standard library to take. But I
can see how it could take an option meaning "place on the next
appropriate address".
> 2. There is a 16 byte header before myClasses[0].a
> Is this for class overhead?
D classes have two pointers as overhead:
* A pointer to the virtual function pointer table of that class type.
* Monitor, another pointer, which I heard is a concept borrowed from C#.
Monitor allows class instances to be used as thread syncronization
primitives.
When the monitor is not needed (i.e. almost always), you can define the
class as extern(C++):
extern (C++)
class Foo {
// ...
}
Now there is less overhead because there is no monitor.
Ali
More information about the Digitalmars-d-learn
mailing list