Boost logo

Boost :

From: Dave Dribin (dave-ml_at_[hidden])
Date: 2006-07-21 17:04:16


On Jul 21, 2006, at 10:51 AM, loufoque wrote:
> Dave Dribin wrote :
>
>> Sometimes these things use unions.
>> It's not necessarily an old C feature.
>
> Have you looked at boost.variant ?

I hadn't until just now.

> It allows similar semantic functionality.

Eh... it may be similar semantically, but it doesn't fit the same use
cases. First, this doesn't work:

   boost::variant< big4_t, little4_t > u(42);

You get a 3,300 character error message, the gist of which is:

   error: call of overloaded 'initialize(void*, const int&)' is
ambiguous

Second, variant provides no guarantee of memory layout.

     boost::variant< big4_t, uint32_t > u(42);
     std::cout << sizeof(u) << std::endl;

provides an output of 8. The whole point of a union is to have to
structure members share the same memory locations. This union
(assuming you could actually use these in unions) has a sizeof 4:

union {
   big4_t big;
   little4_t little;
} big_or_little;

> It's an illegimate use of a factory.
> According to the RAII idiom, the resource should be acquired
> through its
> constructor.

Well, I guess that's a matter of opinion. We're not really acquire
any resources here, so it seems okay to break the idiom. I think
it's a happy-medium workaround for a restriction of the C++ language.

Remember that the whole point of these endian classes is to abstract
away physical memory, and give you complete control over the
alignment and endianness of binary data. You *want* to use these in
structures because you can guarantee padding and endiannes of the
underlying memory. They're not your typical C++ abstractions.
They're necessarily low-level. Which is why, in my opinion, they
should be allowed in unions. A unions sole purpose is to provide
different overlays on top of memory.

Just my $.02,

-Dave


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk