Forms the symbols available to all D programs. Includes Object, which is the root of the class object hierarchy. This module is implicitly imported.
All D class objects inherit from Object.
Convert Object to a human readable string.
nothrow @trusted size_t
toHash();
Compute hash function for Object.
Compare with another Object obj.
Returns:| this < obj | < 0 |
| this == obj | 0 |
| this > obj | > 0 |
Test whetherthis is equal too. The default implementation only compares by identity (using theis operator). Generally, overrides and overloads foropEquals should attempt to compare objects by their contents. A class will most likely want to add an overload that takes your specific type as the argument and does the content comparison. Then you can override this and forward it to your specific typed overload with a cast. Remember to check fornull on the typed overload.
Examples:class Child {int contents;// the typed overload first. It can use all the attribute you wantboolopEquals(const Child c)const @safepurenothrow @nogc {if (cisnull)returnfalse;returnthis.contents == c.contents; }// and now the generic override forwards with a castoverrideboolopEquals(Objecto) {returnthis.opEquals(cast(Child)o); }} static Object
factory(string
classname);
Create instance of class specified by the fully qualified name classname. The class must either have no constructors or have a default constructor.
Example
module foo.bar;class C{this() { x = 10; }int x;}void main(){auto c =cast(C)Object.factory("foo.bar.C");assert(c !isnull && c.x == 10);}
bool
opEquals(LHS, RHS)(LHS
lhs, RHS
rhs)
if ((is(LHS : const(Object)) || is(LHS : shared(const(Object)))) && (is(RHS : const(Object)) || is(RHS : shared(const(Object)))));
Implementation for class opEquals override. Calls the class-defined methods after a null check. Please note this is not nogc right now, even if your implementation is, because of the typeinfo name string compare. This is because of dmd's dll implementation. However, it can infer to @safe if your class' opEquals is.
Examples:If aliased to the same object or both null => equal
class F {int flag;this(int flag) {this.flag = flag; } }F f;assert(f == f);// both nullf =new F(1);assert(f == f);// both aliased to the same object Examples:If either is null => non-equal
class F {int flag;this(int flag) {this.flag = flag; } }F f;assert(!(new F(0) == f));assert(!(f ==new F(0))); Examples:If same exact type => one call to method opEqualsThis test passes
@safe because it defines a new opEquals with
@safeclass F{int flag;this(int flag) {this.flag = flag; }boolopEquals(const F o)const @safenothrowpure {return flag == o.flag; }}F f;assert(new F(0) ==new F(0));assert(!(new F(0) ==new F(1))); Examples:General case => symmetric calls to method opEquals
int fEquals, gEquals;class Base{int flag;this(int flag) {this.flag = flag; }}class F : Base{this(int flag) {super(flag); }boolopEquals(const Base o) @safe { fEquals++;return flag == o.flag; }}class G : Base{this(int flag) {super(flag); }boolopEquals(const Base o) @safe { gEquals++;return flag == o.flag; }}assert(new F(1) ==new G(1));assert(fEquals == 1);assert(gEquals == 1); Examples:This test shows an example for a comprehensive inheritance equality chain too.
staticclass Base{int member;this(int member)pure @safenothrow @nogc {this.member = member; }overrideboolopEquals(Objectrhs)const {returnthis.opEquals(cast(Base)rhs); }boolopEquals(const Baserhs)const @nogcpurenothrow @safe {if (rhsisnull)returnfalse;returnthis.member ==rhs.member; }}// works through the direct class with attributes enabled, except for pure and nogc in the current TypeInfo implementationbool testThroughBase()nothrow @safe{ Base b1 =new Base(0); Base b2 =new Base(0);assert(b1 == b2); Base b3 =new Base(1);assert(b1 != b3);returntrue;}staticassert(testThroughBase());// also works through the base class interface thanks to the override, but no more attributesbool testThroughObject(){ Object o1 =new Base(0); Object o2 =new Base(0);assert(o1 == o2); Object o3 =new Base(1);assert(o1 != o3);returntrue;}staticassert(testThroughObject());// Each time you make a child, you want to override all old opEquals// and add a new overload for the new child.staticclass Child : Base{int member2;this(int member,int member2)pure @safenothrow @nogc {super(member);this.member2 = member2; }// override the whole chain so it works consistently though any baseoverrideboolopEquals(Objectrhs)const {returnthis.opEquals(cast(Child)rhs); }overrideboolopEquals(const Baserhs)const {returnthis.opEquals(cast(const Child)rhs); }// and then add the new overload, if necessary, to handle new membersboolopEquals(const Childrhs)const @nogcpurenothrow @safe {if (rhsisnull)returnfalse;// can call back to the devirtualized base test with implicit conversion// then compare the new member too. or we could have just compared the base// member directly here as well.return Base.opEquals(rhs) &&this.member2 ==rhs.member2; }// a mixin template, of course, could automate this.}bool testThroughChild(){ Child a =new Child(0, 0); Child b =new Child(0, 1);assert(a != b); Base ba = a; Base bb = b;assert(ba != bb); Object oa = a; Object ob = b;assert(oa != ob);returntrue;}staticassert(testThroughChild()); void
setSameMutex(shared Object
ownee, shared Object
owner);
Makes ownee use owner's mutex. This will initialize owner's mutex if it hasn't been set yet.
Parameters:Objectownee | object to change |
Objectowner | source object |
Information about an interface. When an object is accessed via an interface, an Interface* appears as the first entry in its vtbl.
Class info returned bytypeid for this interface (not for containing class)
offset to Interface 'this' from Object 'this'
Array of pairs giving the offset and type information for each member in an aggregate.
Offset of member from start of object
TypeInfo for this member
Runtime type information about a type. Can be retrieved for any type using a
TypeidExpression.
nothrow @trusted size_t
getHash(scope const void*
p) const;
Computes a hash of the instance of a type.
Parameters:void*p | pointer to start of instance of the type |
bool
equals(in void*
p1, in void*
p2) const;
Compares two instances for equality.
int
compare(in void*
p1, in void*
p2) const;
Compares two instances for <, ==, or >.
pure nothrow @nogc @property @safe size_t
tsize() const;
Returns size of the type.
void
swap(void*
p1, void*
p2) const;
Swaps two instances of the type.
pure nothrow @nogc @property inout(TypeInfo)
next() inout;
Get TypeInfo for 'next' type, as defined by what kind of type this is, null if none.
abstract pure nothrow @nogc @safe const(void)[]
initializer() const;
Return default initializer. If the type should be initialized to all zeros, an array with a null ptr and a length equal to the type size will be returned. For static arrays, this returns the default initializer for a single element of the array, usetsize to get the correct size.
pure nothrow @nogc @property @safe uint
flags() const;
Get flags for type: 1 means GC should scan for pointers, 2 means arg of this type is passed in SIMD register(s) if available
const(OffsetTypeInfo)[]
offTi() const;
Get type information on the contents of the type; null if not available
void
destroy(void*
p) const;
Run the destructor on the object and all its sub-objects
void
postblit(void*
p) const;
Run the postblit on the object and all its sub-objects
pure nothrow @nogc @property @safe size_t
talign() const;
Return alignment of type
nothrow @safe int
argTypes(out TypeInfo
arg1, out TypeInfo
arg2);
Return internal info on arguments fitting into 8byte. See X86-64 ABI 3.2.3
pure nothrow @nogc @property @trusted immutable(void)*
rtInfo() const;
Return info used by the garbage collector to do precise collection.
class
TypeInfo_Class:
object.TypeInfo;
Runtime type information about a class. Can be retrieved from an object instance by using the
typeid expression.
class static initializer (init.length gives size in bytes of class)
class name
virtual function pointer table
interfaces this class implements
base class
inheritance distance from Object
unique signature forname
static const(TypeInfo_Class)
find(scope const char[]
classname);
Search all modules for TypeInfo_Class corresponding to classname.
Returns:null if not found
Create instance of Object represented by 'this'.
final pure nothrow @nogc @trusted bool
isBaseOf(scope const TypeInfo_Class
child) const;
Returns true if the class described bychild derives from or is the class described by thisTypeInfo_Class. Always returns false if the argument is null.
Parameters:TypeInfo_Classchild | TypeInfo for some class |
Returns:true if the class described bychild derives from or is the class described by thisTypeInfo_Class.
An instance of ModuleInfo is generated into the object file for each compiled module.
It provides access to various aspects of the module. It is not generated for betterC.
pure nothrow @nogc @property void function()
tlsctor() const;
Returns:module constructor for thread locals,null if there isn't one
pure nothrow @nogc @property void function()
tlsdtor() const;
Returns:module destructor for thread locals,null if there isn't one
pure nothrow @nogc @property void*
xgetMembers() const;
Returns:address of a module'sconst(MemberInfo)[] getMembers(string) function,null if there isn't one
pure nothrow @nogc @property void function()
ctor() const;
Returns:module constructor,null if there isn't one
pure nothrow @nogc @property void function()
dtor() const;
Returns:module destructor,null if there isn't one
pure nothrow @nogc @property void function()
ictor() const;
Returns:module order independent constructor,null if there isn't one
pure nothrow @nogc @property void function()
unitTest() const;
Returns:address of function that runs the module's unittests,null if there isn't one
pure nothrow @nogc @property immutable(ModuleInfo*)[]
importedModules() const return;
Returns:array of pointers to the ModuleInfo's of modules imported by this one
pure nothrow @nogc @property TypeInfo_Class[]
localClasses() const return;
Returns:array of TypeInfo_Class references for classes defined in this module
pure nothrow @nogc @property string
name() const return;
Returns:name of module,null if no name
The base class of all thrown objects.
All thrown objects must inherit from Throwable. ClassException, which derives from this class, represents the category of thrown objects that are safe to catch and handle. In principle, one should not catch Throwable objects that are not derived fromException, as they represent unrecoverable runtime errors. Certain runtime guarantees may fail to hold when these errors are thrown, making it unsafe to continue execution after catching them.
A message describing the error.
The file name of the D source code corresponding with where the error was thrown from.
The line number of the D source code corresponding with where the error was thrown from.
The stack trace of where the error happened. This is an opaque object that can either be converted tostring, or iterated over with foreach to extract the items in the stack trace (as strings).
TraceDeallocator
infoDeallocator;
If set, this is used to deallocate the TraceInfo on destruction.
pure nothrow @nogc @property @safe inout(Throwable)
next() inout return scope;
Returns:A reference to the next error in the list. This is used when a newThrowable is thrown from inside acatch block. The originally caughtException will be chained to the newThrowable via this field.
pure nothrow @nogc @property @safe void
next(Throwable
tail) scope;
Replace next in chain withtail. UsechainTogether instead if at all possible.
final pure nothrow @nogc ref @system uint
refcount() scope return;
Returns:mutable reference to the reference count, which is 0 - allocated by the GC, 1 - allocated by d_newThrowable(), and >=2 which is the reference count + 1
NoteMarked as@system to discourage casual use of it.
int
opApply(scope int delegate(Throwable)
dg);
Loop over the chain of Throwables.
static pure nothrow @nogc @system Throwable
chainTogether(return scope Throwable
e1, return scope Throwable
e2);
Appende2 to chain of exceptions that starts withe1.
Parameters:Throwablee1 | start of chain (can be null) |
Throwablee2 | second part of chain (can be null) |
Returns:Throwable that is at the start of the chain; null if bothe1 ande2 are null
OverridesObject.toString and returns the error message. Internally this forwards to thetoString overload that takes asink delegate.
void
toString(scope void delegate(in char[])
sink) const;
The Throwable hierarchy uses a toString overload that takes asink delegate to avoid GC allocations, which cannot be performed in certain error situations. Override this toString method to customize the error message.
nothrow @safe const(char)[]
message() const;
Get the message describing the error.
This getter is an alternative way to access the Exception's message, with the added advantage of being override-able in subclasses. Subclasses are hence free to do their own memory managements without being tied to the requirement of providing a
string in a field.
The default behavior is to return the
Throwable.msg field.
Returns:A message representing the cause of theThrowable
class
Exception:
object.Throwable;
The base class of all errors that are safe to catch and handle.
In principle, only thrown objects derived from this class are safe to catch inside acatch block. Thrown objects not derived from Exception represent runtime errors that should not be caught, as certain runtime guarantees may not hold, making it unsafe to continue program execution.
Examples:bool gotCaught;try{thrownewException("msg");}catch (Exception e){ gotCaught =true;assert(e.msg =="msg");}assert(gotCaught); pure nothrow @nogc @safe this(string
msg, string
file = __FILE__, size_t
line = __LINE__, Throwable
nextInChain = null);
Creates a new instance of Exception. The nextInChain parameter is used internally and should always benull when passed by user code. This constructor does not automatically throw the newly-created Exception; thethrow expression should be used for that purpose.
class
Error:
object.Throwable;
The base class of all unrecoverable runtime errors.
This represents the category ofThrowable objects that arenot safe to catch and handle. In principle, one should not catch Error objects, as they represent unrecoverable runtime errors. Certain runtime guarantees may fail to hold when these errors are thrown, making it unsafe to continue execution after catching them.
Examples:bool gotCaught;try{thrownewError("msg");}catch (Error e){ gotCaught =true;assert(e.msg =="msg");}assert(gotCaught); pure nothrow @nogc @safe this(string
msg, Throwable
nextInChain = null);
Creates a new instance of Error. The nextInChain parameter is used internally and should always benull when passed by user code. This constructor does not automatically throw the newly-created Error; thethrow statement should be used for that purpose.
Throwable
bypassedException;
The firstException which was bypassed when this Error was thrown, ornull if noExceptions were pending.
@trusted void
clear(Value, Key)(Value[Key]
aa);
@trusted void
clear(Value, Key)(Value[Key]*
aa);
Removes all remaining keys and values from an associative array.
Parameters:Value[Key]aa | The associative array. |
Examples:autoaa = ["k1": 2];aa.clear;assert("k1" !inaa); T
rehash(T : Value[Key], Value, Key)(T
aa);
T
rehash(T : Value[Key], Value, Key)(T*
aa);
T
rehash(T : shared(Value[Key]), Value, Key)(T
aa);
T
rehash(T : shared(Value[Key]), Value, Key)(T*
aa);
Reorganizes the associative array in place so that lookups are more efficient.
Parameters:Taa | The associative array. |
Returns:The rehashed associative array.
V[K]
dup(T : V[K], K, V)(T
aa);
V[K]
dup(T : V[K], K, V)(T*
aa);
Creates a new associative array of the same size and copies the contents of the associative array into it.
Parameters:Taa | The associative array. |
Examples:autoaa = ["k1": 2];auto a2 =aa.dup;aa["k2"] = 3;assert("k2" !in a2); pure nothrow @nogc @safe auto
byKey(T : V[K], K, V)(T
aa);
pure nothrow @nogc auto
byKey(T : V[K], K, V)(T*
aa);
Returns a
forward range which will iterate over the keys of the associative array. The keys are returned by reference.
If structural changes are made to the array (removing or adding keys), all ranges previously obtained through this function are invalidated. The following example program will dereference a null pointer:
import std.stdio : writeln;auto dict = ["k1": 1,"k2": 2];auto keyRange = dict.byKey; dict.clear; writeln(keyRange.front);// Segmentation fault
Parameters:Taa | The associative array. |
Returns:A forward range referencing the keys of the associative array.
Examples:auto dict = [1:"v1", 2:"v2"];int sum;foreach (v; dict.byKey) sum += v;assert(sum == 3);
pure nothrow @nogc @safe auto
byValue(T : V[K], K, V)(T
aa);
pure nothrow @nogc auto
byValue(T : V[K], K, V)(T*
aa);
Returns a
forward range which will iterate over the values of the associative array. The values are returned by reference.
If structural changes are made to the array (removing or adding keys), all ranges previously obtained through this function are invalidated. The following example program will dereference a null pointer:
import std.stdio : writeln;auto dict = ["k1": 1,"k2": 2];auto valueRange = dict.byValue; dict.clear; writeln(valueRange.front);// Segmentation fault
Parameters:Taa | The associative array. |
Returns:A forward range referencing the values of the associative array.
Examples:auto dict = ["k1": 1,"k2": 2];int sum;foreach (v; dict.byValue) sum += v;assert(sum == 3);foreach (ref v; dict.byValue) v++;assert(dict == ["k1": 2,"k2": 3]);
pure nothrow @nogc @safe auto
byKeyValue(T : V[K], K, V)(T
aa);
pure nothrow @nogc auto
byKeyValue(T : V[K], K, V)(T*
aa);
Returns a
forward range which will iterate over the key-value pairs of the associative array. The returned pairs are represented by an opaque type with
.key and
.value properties for accessing references to the key and value of the pair, respectively.
If structural changes are made to the array (removing or adding keys), all ranges previously obtained through this function are invalidated. The following example program will dereference a null pointer:
import std.stdio : writeln;auto dict = ["k1": 1,"k2": 2];auto kvRange = dict.byKeyValue; dict.clear; writeln(kvRange.front.key,": ", kvRange.front.value);// Segmentation fault
Note that this is a low-level interface to iterating over the associative array and is not compatible with the
Tuple type in Phobos. For compatibility with
Tuple, use
std.array.byPair instead.
Parameters:Taa | The associative array. |
Returns:A forward range referencing the pairs of the associative array.
Examples:auto dict = ["k1": 1,"k2": 2];int sum;foreach (e; dict.byKeyValue){assert(e.key[1] == e.value + '0'); sum += e.value;}assert(sum == 3);foreach (e; dict.byKeyValue) e.value++;assert(dict == ["k1": 2,"k2": 3]); @property Key[]
keys(T : Value[Key], Value, Key)(T
aa);
@property Key[]
keys(T : Value[Key], Value, Key)(T*
aa);
Returns a newly allocated dynamic array containing a copy of the keys from the associative array.
Parameters:Taa | The associative array. |
Returns:A dynamic array containing a copy of the keys.
Examples:autoaa = [1:"v1", 2:"v2"];int sum;foreach (k;aa.keys) sum += k;assert(sum == 3);
@property Value[]
values(T : Value[Key], Value, Key)(T
aa);
@property Value[]
values(T : Value[Key], Value, Key)(T*
aa);
Returns a newly allocated dynamic array containing a copy of the values from the associative array.
Parameters:Taa | The associative array. |
Returns:A dynamic array containing a copy of the values.
Examples:autoaa = ["k1": 1,"k2": 2];int sum;foreach (e;aa.values) sum += e;assert(sum == 3);
inout(V)
get(K, V)(inout(V[K])
aa, K
key, lazy inout(V)
defaultValue);
inout(V)
get(K, V)(inout(V[K])*
aa, K
key, lazy inout(V)
defaultValue);
Ifkey is inaa, returns corresponding value; otherwise it evaluates and returnsdefaultValue.
Parameters:inout(V[K])aa | The associative array. |
Kkey | The key. |
inout(V)defaultValue | The default value. |
Examples:autoaa = ["k1": 1];assert(aa.get("k1", 0) == 1);assert(aa.get("k2", 0) == 0); ref V
require(K, V)(ref V[K]
aa, K
key, lazy V
value = V.init);
Ifkey is inaa, returns corresponding value; otherwise it evaluatesvalue, adds it to the associative array and returns it.
Parameters:V[K]aa | The associative array. |
Kkey | The key. |
Vvalue | The required value. |
Examples:autoaa = ["k1": 1];assert(aa.require("k1", 0) == 1);assert(aa.require("k2", 0) == 0);assert(aa["k2"] == 0); void
update(K, V, C, U)(ref V[K]
aa, K
key, scope C
create, scope U
update)
if (is(typeof(create()) : V) && (is(typeof(update(aa[K.init])) : V) || is(typeof(update(aa[K.init])) == void)));
Callscreate ifkey doesn't exist in the associative array, otherwise callsupdate.create returns a corresponding value forkey.update accepts a key parameter. If it returns a value, the value is set forkey.
Parameters:V[K]aa | The associative array. |
Kkey | The key. |
Ccreate | The callable to create a value forkey. Must return V. |
Uupdate | The callable to call ifkey exists. Takes a K argument, returns a V or void. |
Examples:int[string]aa;// createaa.update("key", () => 1, (int) {}// not executed );assert(aa["key"] == 1);// update value by refaa.update("key", () => 0,// not executed (refint v) { v += 1; });assert(aa["key"] == 2);// update from return valueaa.update("key", () => 0,// not executed (int v) => v * 2 );assert(aa["key"] == 4);// 'update' without changing valueaa.update("key", () => 0,// not executed (int) {// do something else });assert(aa["key"] == 4); size_t
hashOf(T)(auto ref T
arg, size_t
seed);
size_t
hashOf(T)(auto ref T
arg);
Calculates the hash value ofarg with an optionalseed initial value. The result might not be equal totypeid(T).getHash(&arg).
Parameters:Targ | argument to calculate the hash value of |
size_tseed | optionalseed value (may be used for hash chaining) |
Returncalculated hash value ofarg
Examples:class MyObject{ size_t myMegaHash()const @safepurenothrow {return 42; }}struct Test{int a; string b; MyObject c; size_t toHash()constpurenothrow { size_t hash = a.hashOf(); hash = b.hashOf(hash); size_t h1 = c.myMegaHash(); hash = h1.hashOf(hash);//Mix two hash valuesreturn hash; }} immutable size_t[pointerBitmap.length]
RTInfoImpl(size_t[] pointerBitmap);
Create RTInfo for type T
enum immutable(void)*
rtinfoNoPointers;
shortcuts for the precise GC, also generated by the compiler used instead of the actual pointer bitmap
@property auto
dup(T)(T[]
a)
if (!is(const(T) : T));
@property T[]
dup(T)(const(T)[]
a)
if (is(const(T) : T));
Provide the .dup array property.
Examples:auto arr = [1, 2];auto arr2 = arr.dup;arr[0] = 0;assert(arr == [0, 2]);assert(arr2 == [1, 2]);
@property immutable
(T)[]
idup(T)(T[]
a);
@property immutable(T)[]
idup(T : void)(const(T)[]
a);
Provide the .idup array property.
Examples:char[] arr = ['a', 'b', 'c'];string s = arr.idup;arr[0] = '.';assert(s =="abc");
pure nothrow @property @trusted size_t
capacity(T)(T[]
arr);
(Property) Gets the current capacity of a slice. The capacity is the sizethat the slice can grow to before the underlying array must bereallocated or extended.
If an append must reallocate a slice with no possibility of extension, then0 is returned. This happens when the slice references a static array, orif another slice references elements past the end of the current slice.
NoteThe capacity of a slice may be impacted by operations on other slices.
Examples://Static array slice: no capacityint[4] sarray = [1, 2, 3, 4];int[] slice = sarray[];assert(sarray.capacity == 0);//Appending to slice will reallocate to a new arrayslice ~= 5;assert(slice.capacity >= 5);//Dynamic array slicesint[] a = [1, 2, 3, 4];int[] b = a[1 .. $];int[] c = a[1 .. $ - 1];debug(SENTINEL) {}else// non-zero capacity very much depends on the array and GC implementation{assert(a.capacity != 0);assert(a.capacity == b.capacity + 1);//both a and b share the same tail}assert(c.capacity == 0);//an append to c must relocate c. pure nothrow @trusted size_t
reserve(T)(ref T[]
arr, size_t
newcapacity);
Reserves capacity for a slice. The capacity is the sizethat the slice can grow to before the underlying array must bereallocated or extended.
Returns:The new capacity of the array (which may be larger thanthe requested capacity).
Examples://Static array slice: no capacity. Reserve relocates.int[4] sarray = [1, 2, 3, 4];int[] slice = sarray[];auto u = slice.reserve(8);assert(u >= 8);assert(&sarray[0] !is &slice[0]);assert(slice.capacity == u);//Dynamic array slicesint[] a = [1, 2, 3, 4];a.reserve(8);//prepare a for appending 4 more itemsauto p = &a[0];u = a.capacity;a ~= [5, 6, 7, 8];assert(p == &a[0]);//a should not have been reallocatedassert(u == a.capacity);//a should not have been extended
nothrow ref @system inout(T[])
assumeSafeAppend(T)(auto ref inout(T[])
arr);
Assume that it is safe to append to this array. Appends made to this arrayafter calling this function may append in place, even if the array was aslice of a larger array to begin with.
Use this only when it is certain there are no elements in use beyond thearray in the memory block. If there are, those elements will beoverwritten by appending to this array.
WarningCalling this function, and then using references to data located after thegiven array results in undefined behavior.
Returns:The input is returned.
Examples:int[] a = [1, 2, 3, 4];// Without assumeSafeAppend. Appending relocates.int[] b = a [0 .. 3];b ~= 5;assert(a.ptr != b.ptr);debug(SENTINEL) {}else{// With assumeSafeAppend. Appending overwrites.int[] c = a [0 .. 3]; c.assumeSafeAppend() ~= 5;assert(a.ptr == c.ptr);} void
destroy(bool initialize = true, T)(ref T
obj)
if (is(T == struct));
void
destroy(bool initialize = true, T)(T
obj)
if (is(T == class));
void
destroy(bool initialize = true, T)(T
obj)
if (is(T == interface));
void
destroy(bool initialize = true, T)(ref T
obj)
if (__traits(isStaticArray, T));
void
destroy(bool initialize = true, T)(ref T
obj)
if (!is(T == struct) && !is(T == interface) && !is(T == class) && !__traits(isStaticArray, T));
Destroys the given object and optionally resets to initial state. It's used todestroy an object, calling its destructor or finalizer so it no longerreferences any other objects. It doesnot initiate a GC cycle or freeany GC memory.Ifinitialize is suppliedfalse, the object is considered invalid afterdestruction, and should not be referenced.
Examples:Reference type demonstration
class C{struct Agg {staticint dtorCount;int x = 10; ~this() { dtorCount++; } }staticint dtorCount; string s ="S"; Agg a; ~this() { dtorCount++; }}C c =new C();assert(c.dtorCount == 0);// destructor not yet calledassert(c.s =="S");// initial state `c.s` is `"S"`assert(c.a.dtorCount == 0);// destructor not yet calledassert(c.a.x == 10);// initial state `c.a.x` is `10`c.s ="T";c.a.x = 30;assert(c.s =="T");// `c.s` is `"T"`destroy(c);assert(c.dtorCount == 1);// `c`'s destructor was calledassert(c.s =="S");// `c.s` is back to its inital state, `"S"`assert(c.a.dtorCount == 1);// `c.a`'s destructor was calledassert(c.a.x == 10);// `c.a.x` is back to its inital state, `10` Examples:C++ classes work too
extern (C++)class CPP{struct Agg {__gsharedint dtorCount;int x = 10; ~this() { dtorCount++; } }__gsharedint dtorCount; string s ="S"; Agg a; ~this() { dtorCount++; }}CPP cpp =new CPP();assert(cpp.dtorCount == 0);// destructor not yet calledassert(cpp.s =="S");// initial state `cpp.s` is `"S"`assert(cpp.a.dtorCount == 0);// destructor not yet calledassert(cpp.a.x == 10);// initial state `cpp.a.x` is `10`cpp.s ="T";cpp.a.x = 30;assert(cpp.s =="T");// `cpp.s` is `"T"`destroy!false(cpp);// destroy without initializationassert(cpp.dtorCount == 1);// `cpp`'s destructor was calledassert(cpp.s =="T");// `cpp.s` is not initializedassert(cpp.a.dtorCount == 1);// `cpp.a`'s destructor was calledassert(cpp.a.x == 30);// `cpp.a.x` is not initializeddestroy(cpp);assert(cpp.dtorCount == 2);// `cpp`'s destructor was called againassert(cpp.s =="S");// `cpp.s` is back to its inital state, `"S"`assert(cpp.a.dtorCount == 2);// `cpp.a`'s destructor was called againassert(cpp.a.x == 10);// `cpp.a.x` is back to its inital state, `10` Examples:Value type demonstration
int i;assert(i == 0);// `i`'s initial state is `0`i = 1;assert(i == 1);// `i` changed to `1`destroy!false(i);assert(i == 1);// `i` was not initializeddestroy(i);assert(i == 0);// `i` is back to its initial state `0`
Examples:Nested struct type
int dtorCount;struct A{int i; ~this() { dtorCount++;// capture local variable }}A a = A(5);destroy!false(a);assert(dtorCount == 1);assert(a.i == 5);destroy(a);assert(dtorCount == 2);assert(a.i == 0);// the context pointer is now null// restore it so the dtor can runimport core.lifetime : emplace;emplace(&a, A(0));// dtor also called here template
imported(string moduleName)
Provides an "inline import", i.e. animport that is only available for alimited lookup. For example:
void fun(imported!"std.stdio".File input){ ... use File from std.stdio normally ...}There is no need to import
std.stdio at top level, so
fun carries its owndependencies. The same approach can be used for template constraints:
void fun(T)(imported!"std.stdio".File input, T value)if (imported!"std.traits".isIntegral!T){ ...}An inline import may be used in conjunction with the
with statement as well.Inside the scope controlled by
with, all symbols in the imported module aremade available:
void fun(){with (imported!"std.datetime")with (imported!"std.stdio") { Clock.currTime.writeln; }}The advantages of inline imports over top-level uses of the
import declarationare the following:
- The
imported template specifies dependencies at declaration level, not atmodule level. This allows reasoning about the dependency cost of declarations inseparation instead of aggregated at module level. - Declarations using
imported are easier to move around because they don'trequire top-level context, making for simpler and quicker refactorings. - Declarations using
imported scale better with templates. This is becausetemplates that are not instantiated do not have their parameters and constraintsinstantiated, so additional modules are not imported without necessity. Thismakes the cost of unused templates negligible. Dependencies are pulled on a needbasis depending on the declarations used by client code.
The use of
imported also has drawbacks:
- If most declarations in a module need the same imports, then factoring themat top level, outside the declarations, is simpler than repeating them.
- Traditional dependency-tracking tools such as make and other build systemsassume file-level dependencies and need special tooling (such as rdmd) in orderto work efficiently.
- Dependencies at the top of a module are easier to inspect quickly thandependencies spread throughout the module.
See Also:The
forum discussion that led to the creation of the
imported facility. Credit isdue to Daniel Nielsen and Dominikus Dittes Scherkl.