Alternative destructors, do/should we have them?
Dukc
ajieskola at gmail.com
Thu Jul 5 10:57:51 UTC 2018
D does not have default constructors for structs, but I have
thought that this might get around the problem:
struct MallocedPtr()
{ void* location;
~this()
{ import core.stdc.stdlib;
assert(location != null);
free(location.ptr);
}
}
Unlike a destructor which has a runtime check whether it's
initialized, this has no performance cost over a C++-style
default-initialized struct. I think "hand grenade RAII" is a
perfect name for this idiom, because like a hand grenade, this
struct asserts it is set somewhere else after initialization
before it's destructor runs.
But there is a problem. If you use std.algorithm.move to give a
hand grenade to a function, it initializes another hand grenade
for the calling function. I didn't come up with any way to defuse
the initialized grenade without runtime cost.
Granted, a runtime check at destructor is unlikely to be a major
performance hit for any normal application, but D is a systems
language, right? Do you have any ideas to get around this? If
not, should we in your opinion have an ability to define an
alternative destructor which runs only when explicitly requested?
More information about the Digitalmars-d
mailing list