auto -> auto & var

Derek Parnell derek at psych.ward
Sat Mar 18 03:53:02 PST 2006


On Mon, 13 Mar 2006 23:03:47 +1100, Lionello Lunesu  
<lio at remove.lunesu.com> wrote:

>
> "Kramer" <Kramer_member at pathlink.com> wrote in message
> news:duspas$2dfo$1 at digitaldaemon.com...
>> I keep tripping myself over the double meaning of auto.  I know it
>> shouldn't be
>> that difficult to remember that auto means type inference and also stack
>> allocation/RAII, but does it have to be that way?
>
> Walter explained it: it does not have two meanings. The "auto" merely
> notifies the compiler (or lexer, I don't know) that it's a declaration  
> and a
> variable name will follow.
>
> When the compiler encounters "auto x" it knows "x" is a variable. Since
> "auto x" doesn't mention a type, it'll be derived.. Same thing for  
> "static
> x", x must be a variable, but there's no type so it'll be derived.

This seems to be true, however the RAII behaviour is not invoked when this  
syntax is used. So how does one declare an auto-type-infered and an  
auto-RAII variable? For some example code ...

import std.stdio;
class bar
{
     this() { writefln("ctor bar"); }
     ~this(){ writefln("dtor bar"); }
}

int foo()
{
     auto bar a = new bar;
     return a.sizeof;
}

int xyz()
{
     auto a = new bar;
     return a.sizeof;
}

void main()
{
     writefln("foo: %s", foo());
     writefln("xyz: %s", xyz());
}


===========
output:

ctor bar
dtor bar
foo: 4
ctor bar
xyz: 4
dtor bar
===========

Which seems to be showing that 'auto bar a = new bar;' is needed for RAII  
behaviour and just 'auto a = new bar;' does type inference but no RAII.  
And if one uses 'auto auto a = new bar' we get the compiler error  
"redundant storage class 'auto'".

-- 
Derek Parnell
Melbourne, Australia



More information about the Digitalmars-d mailing list