Opaque structs

monarch_dodra monarchdodra at gmail.com
Sat Jun 29 07:38:05 PDT 2013


On Saturday, 29 June 2013 at 12:58:51 UTC, Johannes Pfau wrote:
> Am Sat, 29 Jun 2013 10:54:32 +0200
> schrieb "Maxim Fomin" <maxim at maxim-fomin.ru>:
>
>> On Saturday, 29 June 2013 at 08:01:17 UTC, Johannes Pfau wrote:
>> > Am Fri, 28 Jun 2013 22:16:33 +0200
>> > schrieb Andrej Mitrovic <andrej.mitrovich at gmail.com>:
>> >
>> >> On 6/28/13, Johannes Pfau <nospam at example.com> wrote:
>> >> > A naive question: Why isn't struct S {} enough? This 
>> >> > should be a
>> >> > struct with size 0 so why do we need to disable the 
>> >> > constructor and
>> >> > postblit explicitly?
>> >> 
>> >> Because the user should never be able to use such a struct 
>> >> by value,
>> >> in other words a user might mistakenly write code such as:
>> >> 
>> >>     S s2 = *s;  // copies 1 byte
>> >
>> > But why is that legal / does that copy _one_ byte? It seems 
>> > like that's
>> > totally arbitrary. Shouldn't doing anything value-related on
>> > an empty struct be invalid anyway?
>> 
>> It copies one byte because empty structs have one byte - 
>> according to D implementation. The value can be adjusted using 
>> align() atrribute.
>
> I see. I didn't know that we have this in the spec, but I guess 
> there's
> some good reason for this behavior if it was explicitly 
> specified /
> implemented.

For the same reasons as in C/C++, "[they] require empty classes 
to have non-zero size to ensure object identity". For example, 
calculating the size of an array using:
"size_t size = sizeof(arr) / sizeof(arr[0])"
Requires the object's size to be non null.

Iterating with:
s* it = arr;
s* it_end = arr + size;
for ( ; it != it_end ; ++it )
{}
Requires the objects to take up space.



More information about the Digitalmars-d-learn mailing list