Hacker News new | ask | show | jobs
by kstenerud 5524 days ago
What you really want is something along the lines of:

    void myMethod()
    {
        disposable File myFile = new File(somePath);

        // ... do stuff with the file

        // "disposable" modifier causes myFile to be
        // forcibly destroyed upon leaving scope for any
        // reason (except if the disposable object itself
        // is returned from the method).
    }
An idiom designed specifically for the purpose of resource management would make for a far cleaner implementation than shoehorning an existing mechanism.

You'd probably also need to add checking for references to the object by still-living objects (i.e. objects not eligible for gc). If any live object has a reference to the disposable object, its "disposable" status gets removed. Similarly, returning the disposable object from the method also strips its "disposable" status. It would add extra processing at the end of the scope level, but generally methods that create/use resources don't need to be lightning fast anyway.

You could even add the "disposable" modifier to class definitions, making all instances of that class disposable by default (and thus destroyed unless referenced or returned).

2 comments

It's not so easy because what happens if you have code like this:

  static File globalFile;
  
  void register_file(File aFile)
  {
      globalFile = aFile;
  }
  
  void myMethod()
  {
      disposable File myFile = new File(somePath);
  
      register_file(myFile);
  }
If you answer, "add referencing counting", reference counting isn't perfect because you can create cyclic references.

The only reason RAII works in C++ is because you can refer to an object by value and separately by reference. You can create stack-based objects that have a defined scope.

You really can't have this in a language that always treats objects only by reference.

My answer would be to create a shortcut in the existing reference system of the gc. Invoke a subset of the gc which checks a reduced list of object references made from that scope or deeper.

Reference counted systems only work if you don't create cyclic (strong) references, so that argument is moot. In fact, reference counted systems can deal with resource objects easily so long as the compiler/interpreter ensures that pending autoreleases are executed when unwinding the stack during an exception.

Isn't that exactly what reference counting ala shared_ptr does?