|
|
|
|
|
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). |
|
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.