Walter: Before you go and implement the new RAII syntax..

Derek Parnell derek at nomail.afraid.org
Wed Sep 6 21:57:51 PDT 2006


On Wed, 06 Sep 2006 21:07:15 -0700, Walter Bright wrote:

> Derek Parnell wrote:
>> BTW, I'm not wedded to 'local' but something, ... anything, that explicitly
>> informs the reader that the object will be destroyed when it goes out of
>> scope is needed. Leaving it out is not a good user interface.
> 
> Why? It's implicit in C style programming languages that things 
> disappear when they go out of scope. It's the original meaning of 'auto' 
> in C and C++, it's also the default behavior.

(N.B: I'm talking about the proposed situation where the D 'auto' keyword
is *not* used to implement RAII.)

Because D doesn't work that way. Sometimes, even when the object goes out
of scope, the object is not destroyed - that is, the dtor is not guaranteed
to be called. However, if you use a 'auto' object the dtor is called.


 import std.stdio;
 class Foo
 {
  static int s_cnt;
  int m_cnt;
  char[] m_id;

  this(char[] id) { m_id = id.dup; 
                    s_cnt++; m_cnt = s_cnt; 
                    writefln(m_id," CTOR", m_cnt); }
  ~this() { writefln(m_id, " DTOR", m_cnt);}
 }

 void func(char[] id)
 {
   Foo a =  new Foo(id);
   auto Foo b = new Foo(id);


   // the dtor for 'a' is not necessarily called on func exit.
   // the dtor for 'b' is always called on func exit.
 }


 void main()
 {

    func("A");
    func("B");
    func("C");
    func("D");

 } 

The output from this is ...

A CTOR1
A CTOR2
A DTOR2
B CTOR3
B CTOR4
B DTOR4
C CTOR5
C CTOR6
C DTOR6
D CTOR7
D CTOR8
D DTOR8
D DTOR7
C DTOR5
B DTOR3
A DTOR1

which clearly shows that the currently 'auto' objects are destroyed on
scope exit but non-auto ones are not.

My earlier discussion was focused on replacing the 'auto' keyword for RAII
with a more meaningful keyword, such as 'local'. All I was saying was that
I don't care so much which new keyword is used to replace 'auto' so long as
it gives a better clue to the reader that a variable so decorated *WILL* be
destroyed at scope end, as will its referenced object if any.

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
7/09/2006 2:38:38 PM



More information about the Digitalmars-d mailing list