Behavior of "auto"

Kirk McDonald kirklin.mcdonald at gmail.com
Wed Dec 5 23:56:24 PST 2007


Derek Parnell wrote:
> On Thu, 6 Dec 2007 06:20:53 +0000 (UTC), NullTerminator wrote:
> 
> 
>>== Repost the article of NullTerminator (NullTerminator at Hotmail.com)
>>== Posted at 2007/12/06 01:07 to D
>>
>>A strange effect of using auto:
>>
>>The following code:
>>import std.stdio;
>>
>>class Test {
>>   this() {
>>      printf("Created\n");
>>   }
>>
>>   ~this() {
>>      printf("Destroyed\n");
>>   }
>>}
>>
>>int main(char[][] args){
>>   for (int n = 0; n < 10; n++)
>>      Test t = new Test();
>>   return 0;
>>}
>>
>>produces the following output:
>>Created
>>Created
>>Created
>>Created
>>Created
>>Created
>>Created
>>Created
>>Created
>>Created
>>Destroyed
>>Destroyed
>>Destroyed
>>Destroyed
>>Destroyed
>>Destroyed
>>Destroyed
>>Destroyed
>>Destroyed
>>Destroyed
>>
>>where as changing the line:
>>      Test t = new Test();
>>to:
>>      auto Test t = new Test();
>>produces:
>>Created
>>Destroyed
>>Created
>>Destroyed
>>Created
>>Destroyed
>>Created
>>Destroyed
>>Created
>>Destroyed
>>Created
>>Destroyed
>>Created
>>Destroyed
>>Created
>>Destroyed
>>Created
>>Destroyed
>>Created
>>Destroyed
>>
>>As I understand it, one would expect this to be the effect of "scope," not
>>"auto."  Can someone explain why this happens?
> 
> 
> Both 'scope' and 'auto' are poorly documented. However, the variable
> declared with an 'auto' is scoped to the block it is declared in and is
> destroyed when going out of scope. In effect 'auto' is shorthand for 'scope
> <type>' ...
> 
> That is to say ...
> 
>   auto t = new Test();
> 
> is equivalent to ...
> 
>   scope Test t = new Test();
>    
> 

This is not true. The situation is more complex.

Prior to DMD 0.174, 'auto' was used for both type inference and scoped 
destruction. That is to say, this:

     auto obj = new C; // infer the type of 'obj'

Was different than this:

     auto C obj = new C; // destroy 'obj' at the end of scope

This behavior was considered confusing enough that the 'scope' keyword 
(which was already in the language for scope guards) was allowed in 
place of auto in the latter case:

     scope C obj = new C; // destroy 'obj' at the end of scope

The use of 'auto' to mean scoped destruction was promptly forgotten as 
fast as people could. However, as the original poster discovered, this 
meaning is still allowed.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org



More information about the Digitalmars-d mailing list