Boost logo

Boost :

From: Joel de Guzman (joel_at_[hidden])
Date: 2008-06-03 20:41:07


Marco Costalba wrote:

> Here it is another undocumented behaviour of boost::fusion.
>
> Did you know that dereferencing a fusion iterator to a mpl sequence
> causes a duplication of the pointed object?
>
> Following the test code:
>
>
> static int cnt = 0;
>
> struct Test
> {
> Test() { cnt++; }
> };
>
> using namespace boost::fusion;
>
> int main(int, char**)
> {
> typedef boost::mpl::vector<Test,Test> Mpl_vec;
>
> Mpl_vec mpl_vec;
>
> result_of::begin<Mpl_vec>::type iter = begin(mpl_vec);
>
> cout << cnt << endl; // prints 0
>
> deref(iter);
>
> cout << cnt << endl; // prints 1
>
> *iter;
>
> cout << cnt << endl; // prints 2
>
> return 0;
> }
>
> I found this while traversing a sequence with fusion::for_each because
> code started to create a lot of copies of the sequence elements,
> indeed the whole sequence is duplicated each time it's traversed with
> fusion::for_each !!
>
> Is this foreseen or it's a bug.

It's a feature ;-)... Here's why:

mpl sequences do not have storage. So how do you get a value?
You get it whenever you dereference an iterator. It's computed
on the fly, so to speak. It's generated. If that's not what you
want, first make a fusion /container/ from the mpl sequence.

Regards,

-- 
Joel de Guzman
http://www.boost-consulting.com
http://spirit.sf.net

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