tni wrote:
> On 2010-08-22 10:53, Kai-Uwe Bux wrote:
>> Juha Nieminen wrote:
>>
>>> But yes: If a C program is using the struct hack solely for the
>>> same purpose as you would normally use std::vector (in other words,
>>> the struct only contains the array size plus the array itself),
>>> then std::vector would definitely be the better choice in the
>>> equivalent C++ program. However, as said, the struct hack can be used
>>> for more than that.
>>
>> Now, you made me curious. Could you present an example? I would try
>> to rewrite that without performance penalty in a "hack free" manner.
>> The reasong is: I have a hard time imagining a use for the struct
>> hack in C++ such that doing the same thing in a more idiomatic way
>> comes with a performance hit. On the other hand, I know that
>> sometimes my imagination is just lacking.
>
> How about this:
>
> #include <boost/intrusive/bs_set_hook.hpp>
> #include <boost/intrusive/treap.hpp>
>
> struct Message : public boost::intrusive::bs_set_base_hook<> {
> uint16_t priority;
> uint16_t length;
> uint8_t payload[];
> };
>
> // Message comparison for treap is based on payload
> boost::intrusive::treap<Message> mtreap;
>
> Let's assume, you have to use a treap-like data structure, but you are
> free to distribute the data any way you like. "bs_set_base_hook<>" is
> basically a set of 3 pointers (to other messages). Whenever you
> access a message, you typically use priority, length, payload and a
> random pointer from "bs_set_base_hook<>".
>
> The messages are small, lets say on average 16 bytes. Let's assume on
> a 32-bit platform, sizeof(Message) will be 16 without payload and
> pointers are 4 bytes each, so messages will typically fit into a
> single cache line.
> Let's assume for the purposes of this example, access to the messages
> is random and memory usage is more than 100x the CPU cache size.
>
> Given these constraints, the only choice you have, is to locate all
> the data for a message in one place. You could of course use a vector
> with something like the small string optimization (instead of the
> flexible array). That would result in higher memory usage and more
> complex code but a much cleaner design/interface and re-usability.
>
> \\
>
> That being said, I'll happily admit that you can usually
> hide/eliminate the extra indirection 'proper' C++ requires and that
> the struct hack should be used very, very rarely.
Those selective placements though are very, very important. Perhaps
having come from a C originally I still have an appreciation for
programming close to the metal whereas that concept escapes those that
started out with the decidely higher-level C++ (or buy into it, lock,
stock and barrel).
|