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

Garett Bass garettbass at studiotekne.com
Wed Sep 6 16:44:43 PDT 2006


I'd like to note some problems that all of these approaches face.

Jarrett Billingsley wrote:
> 
> Foo f = stack Foo();

Jarrett's proposed 'stack' allocation specifier is interesting in that it seems to indicate that the object currently referenced by f will be deleted even if a later line of code does something ugly like this:

    f = stack Foo(); // assign a different Foo to f

Now both Foo objects will be *deallocated* as the stack unwinds, but it is not clear whether the destructor can be called on the unreferenced Foo, unless it is called during the reassignment process.

Alternatively, either of these current implementations happily leaves one Foo object dangling on the heap:

    auto Foo g = new Foo();
    g = new Foo(); // drops reference to original Foo

    Foo g = new Foo(); scope(exit) delete g;
    g = new Foo(); // drops reference to original Foo

How does the GC maintain these dropped references?  This seems like an easy bug to insert, and potentially a difficult one to find.

It is unfortunate that true stack object instances do not exist in D.  The 'stack' syntax defies D's current heap-only object allocation philosophy.

Another advantage of C++ style stack object instances is the ability to overload the assignment operator, which allows an object instance to be treated as a built-in type.  You can't do this in D because it would alias your ability to reassign the object reference to another object.  C++ has no problem implementing real and imaginary numbers as classes, they need not be built-in types since their instances can be treated as such syntactically.

I don't understand why modern high-level languages are so quick to discard (or bias against) the pointer.  The distinction between object references/pointers and object instances is very valuable in C++.  It can be nice to know that no other code is going to reassign another object to your variable.

Pissing in the wind,
Garett



More information about the Digitalmars-d mailing list