Obtaining aligned addresses and aligned spaces for objects
Steven Schveighoffer
schveiguy at yahoo.com
Wed Jun 29 10:43:51 PDT 2011
On Wed, 29 Jun 2011 13:29:07 -0400, Ali Çehreli <acehreli at yahoo.com> wrote:
> On Wed, 29 Jun 2011 10:47:39 -0400, Steven Schveighoffer wrote:
>
>> On Wed, 29 Jun 2011 01:42:37 -0400, Ali Çehreli <acehreli at yahoo.com>
>> wrote:
>>> On a related note, why doesn't __traits(classInstanceSize, T) consider
>>> the padding bytes? If I'm not mistaken struct sizes do include the
>>> padding bytes. The following class has the very odd size of 17! Is that
>>> by design?
>>
>> Probably it's because classes are intended to occupy their own memory
>> block, so the pad doesn't matter, you can't put two in the same block
>> anyways.
>
> You also say a block is 16 bytes below but the following program seems to
> be able to put objects at 24 byte intervals.
Yes, it depends on the contents of the class. All I was saying is that
the GC already aligns all blocks to 16-byte boundaries, so the language
simply doesn't worry about class alignment and padding.
>> But I don't think
>> it would work great if you put two classes in the same block without
>> significant compiler/GC changes.
>>
>> That being said, given that all GC blocks are at least 16-byte aligned,
>> the same should hold true for any class instance.
>
> I am able to place class objects at 24 byte intervals with the following
> program, which indicates that some objects straddle block boundaries. Is
> that fine? Is the following method sufficient. Am I doing things
> unnecessarily complicated?
A "block" is not a 16-byte space, it's simply a chunk of memory. You are
not straddling block boundaries, because you have everything in one block.
Note that your test is not very taxing on alignment -- char does not need
to be aligned. I would test with reals and also try and test the hidden
elements of classes -- the vtable (i.e. virtual functions), interfaces,
and the monitor object (i.e. try using synchronized) to ensure everything
is working right.
Note that having data be misaligned may not result in failure, it may just
result in slower execution.
Also note that you must manually destroy these classes via clear -- the GC
only destroys the block, and assumes one class instance per block. And in
fact, you are not setting the finalize flag on the block on creation, so
it wouldn't call any destructors.
-Steve
More information about the Digitalmars-d-learn
mailing list