Implementation of C++0x's "future" syntax

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Sun Jan 14 09:25:35 PST 2007


Daniel Keep wrote:
> struct FutureResult(tFn, tArgs...)
> {
[snip]
>         // start is used as the entry point to the thread
>         int start()
>         {
>             static if( !is( tResult == void ) )
>                 result = fn(args);
>             else
>                 fn(args);
> 
>             got_result = true;
>             return 0;
>         }
[snip]
> FutureResult!(tFn, tArgs) future(tFn, tArgs...)(tFn fn, tArgs args)
> {
>     FutureResult!(tFn, tArgs) result;
> 
>     result.fn = fn;
> 
>     foreach( i,a ; args )
>         result.args[i] = a;
> 
>     result.thread = new Thread(&result.start);
>     result.thread.start();
> 
>     return result;
> }

So you create a struct on the stack, use a delegate to a member function 
as a thread entry-point, then return the struct?
Does that strike anyone else as a Bad Idea(TM)?

The named return value optimization that was recently introduced will 
probably keep this from breaking in typical code, but if 'result' is 
ever returned without that optimization being made this seems likely to 
corrupt stack-based data of new stackframes created afterwards...

I _really_ think FutureResult!() should be heap-allocated. If you want, 
you can even make it a class derived from Thread so no extra allocations 
need to be made.



More information about the Digitalmars-d-announce mailing list