Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.111.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

object

CategorySymbols
ArraysassumeSafeAppend capacity dupidup reserve 
Associative arraysbyKey byKeyValue byValue clear dup get keys rehash require update values 
Generaldestroy hashOf imported noreturn 
ClassesError Exception Object opEquals Throwable 
Type infoInterface ModuleInfo OffsetTypeInfo RTInfoImpl rtinfoNoPointers TypeInfo TypeInfo_Class 
Forms the symbols available to all D programs. Includes Object, which is the root of the class object hierarchy. This module is implicitly imported.
License:
Boost License 1.0.
Authors:
Walter Bright, Sean Kelly

Sourceobject.d

aliasnoreturn =noreturn;
Bottom type. Seenoreturn.
classObject;
All D class objects inherit from Object.
stringtoString();
Convert Object to a human readable string.
nothrow @trusted size_ttoHash();
Compute hash function for Object.
intopCmp(Objecto);
Compare with another Object obj.
Returns:
this < obj< 0
this == obj0
this > obj> 0
boolopEquals(Objecto);
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 Objectfactory(stringclassname);
Create instance of class specified by the fully qualified name classname. The class must either have no constructors or have a default constructor.
Returns:
null if failed

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);}

boolopEquals(LHS, RHS)(LHSlhs, RHSrhs)
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@safe
class 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());
voidsetSameMutex(shared Objectownee, shared Objectowner);
Makes ownee use owner's mutex. This will initialize owner's mutex if it hasn't been set yet.
Parameters:
Objectowneeobject to change
Objectownersource object
structInterface;
Information about an interface. When an object is accessed via an interface, an Interface* appears as the first entry in its vtbl.
TypeInfo_Classclassinfo;
Class info returned bytypeid for this interface (not for containing class)
size_toffset;
offset to Interface 'this' from Object 'this'
structOffsetTypeInfo;
Array of pairs giving the offset and type information for each member in an aggregate.
size_toffset;
Offset of member from start of object
TypeInfoti;
TypeInfo for this member
abstract classTypeInfo;
Runtime type information about a type. Can be retrieved for any type using aTypeidExpression.
nothrow @trusted size_tgetHash(scope const void*p) const;
Computes a hash of the instance of a type.
Parameters:
void*ppointer to start of instance of the type
Returns:
the hash
Bugs:
fixhttps://issues.dlang.org/show_bug.cgi?id=12516 e.g. by changing this to a truly safe interface.
boolequals(in void*p1, in void*p2) const;
Compares two instances for equality.
intcompare(in void*p1, in void*p2) const;
Compares two instances for <, ==, or >.
pure nothrow @nogc @property @safe size_ttsize() const;
Returns size of the type.
voidswap(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 uintflags() 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
voiddestroy(void*p) const;
Run the destructor on the object and all its sub-objects
voidpostblit(void*p) const;
Run the postblit on the object and all its sub-objects
pure nothrow @nogc @property @safe size_ttalign() const;
Return alignment of type
nothrow @safe intargTypes(out TypeInfoarg1, out TypeInfoarg2);
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.
classTypeInfo_Class:object.TypeInfo;
Runtime type information about a class. Can be retrieved from an object instance by using thetypeid expression.
byte[]m_init;
class static initializer (init.length gives size in bytes of class)
stringname;
class name
void*[]vtbl;
virtual function pointer table
Interface[]interfaces;
interfaces this class implements
TypeInfo_Classbase;
base class
ushortdepth;
inheritance distance from Object
uint[4]nameSig;
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
Objectcreate() const;
Create instance of Object represented by 'this'.
final pure nothrow @nogc @trusted boolisBaseOf(scope const TypeInfo_Classchild) 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_ClasschildTypeInfo for some class
Returns:
true if the class described bychild derives from or is the class described by thisTypeInfo_Class.
structModuleInfo;
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 stringname() const return;
Returns:
name of module,null if no name
classThrowable;
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.
stringmsg;
A message describing the error.
stringfile;
The file name of the D source code corresponding with where the error was thrown from.
size_tline;
The line number of the D source code corresponding with where the error was thrown from.
TraceInfoinfo;
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).
TraceDeallocatorinfoDeallocator;
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 voidnext(Throwabletail) scope;
Replace next in chain withtail. UsechainTogether instead if at all possible.
final pure nothrow @nogc ref @system uintrefcount() 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.

intopApply(scope int delegate(Throwable)dg);
Loop over the chain of Throwables.
static pure nothrow @nogc @system ThrowablechainTogether(return scope Throwablee1, return scope Throwablee2);
Appende2 to chain of exceptions that starts withe1.
Parameters:
Throwablee1start of chain (can be null)
Throwablee2second part of chain (can be null)
Returns:
Throwable that is at the start of the chain; null if bothe1 ande2 are null
stringtoString();
OverridesObject.toString and returns the error message. Internally this forwards to thetoString overload that takes asink delegate.
voidtoString(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 astring in a field.
The default behavior is to return theThrowable.msg field.
Returns:
A message representing the cause of theThrowable
classException: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(stringmsg, stringfile = __FILE__, size_tline = __LINE__, ThrowablenextInChain = 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.
classError: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(stringmsg, ThrowablenextInChain = 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.
ThrowablebypassedException;
The firstException which was bypassed when this Error was thrown, ornull if noExceptions were pending.
@trusted voidclear(Value, Key)(Value[Key]aa);

@trusted voidclear(Value, Key)(Value[Key]*aa);
Removes all remaining keys and values from an associative array.
Parameters:
Value[Key]aaThe associative array.
Examples:
autoaa = ["k1": 2];aa.clear;assert("k1" !inaa);
Trehash(T : Value[Key], Value, Key)(Taa);

Trehash(T : Value[Key], Value, Key)(T*aa);

Trehash(T : shared(Value[Key]), Value, Key)(Taa);

Trehash(T : shared(Value[Key]), Value, Key)(T*aa);
Reorganizes the associative array in place so that lookups are more efficient.
Parameters:
TaaThe associative array.
Returns:
The rehashed associative array.
V[K]dup(T : V[K], K, V)(Taa);

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:
TaaThe associative array.
Examples:
autoaa = ["k1": 2];auto a2 =aa.dup;aa["k2"] = 3;assert("k2" !in a2);
pure nothrow @nogc @safe autobyKey(T : V[K], K, V)(Taa);

pure nothrow @nogc autobyKey(T : V[K], K, V)(T*aa);
Returns aforward 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:
TaaThe 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 autobyValue(T : V[K], K, V)(Taa);

pure nothrow @nogc autobyValue(T : V[K], K, V)(T*aa);
Returns aforward 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:
TaaThe 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 autobyKeyValue(T : V[K], K, V)(Taa);

pure nothrow @nogc autobyKeyValue(T : V[K], K, V)(T*aa);
Returns aforward 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 theTuple type in Phobos. For compatibility withTuple, usestd.array.byPair instead.
Parameters:
TaaThe 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)(Taa);

@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:
TaaThe 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)(Taa);

@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:
TaaThe 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, Kkey, lazy inout(V)defaultValue);

inout(V)get(K, V)(inout(V[K])*aa, Kkey, lazy inout(V)defaultValue);
Ifkey is inaa, returns corresponding value; otherwise it evaluates and returnsdefaultValue.
Parameters:
inout(V[K])aaThe associative array.
KkeyThe key.
inout(V)defaultValueThe default value.
Returns:
The value.
Examples:
autoaa = ["k1": 1];assert(aa.get("k1", 0) == 1);assert(aa.get("k2", 0) == 0);
ref Vrequire(K, V)(ref V[K]aa, Kkey, lazy Vvalue = V.init);
Ifkey is inaa, returns corresponding value; otherwise it evaluatesvalue, adds it to the associative array and returns it.
Parameters:
V[K]aaThe associative array.
KkeyThe key.
VvalueThe required value.
Returns:
The value.
Examples:
autoaa = ["k1": 1];assert(aa.require("k1", 0) == 1);assert(aa.require("k2", 0) == 0);assert(aa["k2"] == 0);
voidupdate(K, V, C, U)(ref V[K]aa, Kkey, scope Ccreate, scope Uupdate)
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]aaThe associative array.
KkeyThe key.
CcreateThe callable to create a value forkey. Must return V.
UupdateThe 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_thashOf(T)(auto ref Targ, size_tseed);

size_thashOf(T)(auto ref Targ);
Calculates the hash value ofarg with an optionalseed initial value. The result might not be equal totypeid(T).getHash(&arg).
Parameters:
Targargument to calculate the hash value of
size_tseedoptionalseed 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 autodup(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_tcapacity(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_treserve(T)(ref T[]arr, size_tnewcapacity);
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);}
voiddestroy(bool initialize = true, T)(ref Tobj)
if (is(T == struct));

voiddestroy(bool initialize = true, T)(Tobj)
if (is(T == class));

voiddestroy(bool initialize = true, T)(Tobj)
if (is(T == interface));

voiddestroy(bool initialize = true, T)(ref Tobj)
if (__traits(isStaticArray, T));

voiddestroy(bool initialize = true, T)(ref Tobj)
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
templateimported(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 importstd.stdio at top level, sofun 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 thewith statement as well.Inside the scope controlled bywith, 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 theimport declarationare the following:
  • Theimported 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 usingimported are easier to move around because they don'trequire top-level context, making for simpler and quicker refactorings.
  • Declarations usingimported 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 ofimported 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:
Theforum discussion that led to the creation of theimported facility. Credit isdue to Daniel Nielsen and Dominikus Dittes Scherkl.
Copyright © 1999-2025 by theD Language Foundation | Page generated byDdoc on Fri Oct 10 22:08:14 2025

[8]ページ先頭

©2009-2025 Movatter.jp