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 using a local clone.

object

Forms the symbols available to all D programs. Includes Object, which is the root of the class object hierarchy. This module is implicitly imported.
Authors:
Walter Bright, Sean Kelly
public import core.internal.array.appending : _d_arrayappendTImpl;
public import core.internal.array.appending : _d_arrayappendcTXImpl;
public import core.internal.array.comparison : __cmp;
public import core.internal.array.equality : __equals;
public import core.internal.array.equality : __ArrayEq;
public import core.internal.array.casting : __ArrayCast;
public import core.internal.array.concatenation : _d_arraycatnTXImpl;
public import core.internal.array.construction : _d_arrayctor;
public import core.internal.array.construction : _d_arraysetctor;
public import core.internal.array.capacity : capacity;
public import core.internal.array.capacity : reserve;
public import core.internal.array.capacity : assumeSafeAppend;
public import core.internal.array.capacity : _d_arraysetlengthTImpl;
nothrow void __move_post_blt(S)(ref S newLocation, ref S oldLocation)
if (is(S == struct));
Recursively calls the opPostMove callbacks of a struct and its members if they're defined.
When moving a struct instance, the compiler emits a call to this function after blitting the instance and before releasing the original instance's memory.
Parameters:
S newLocation reference to struct instance being moved into
S oldLocation reference to the original instance

Note This function is tentatively defined as nothrow to prevent opPostMove from being defined without nothrow, which would allow for possibly confusing changes in program flow.

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 : U[n], U, size_t n)(ref T obj)
if (!is(T == struct));

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 to destroy an object, calling its destructor or finalizer so it no longer references any other objects. It does not initiate a GC cycle or free any GC memory. If initialize is supplied false, the object is considered invalid after destruction, and should not be referenced.
Examples:
Reference type demonstration
class C
{
    struct Agg
    {
        static int dtorCount;

        int x = 10;
        ~this() { dtorCount++; }
    }

    static int dtorCount;

    string s = "S";
    Agg a;
    ~this() { dtorCount++; }
}

C c = new C();
assert(c.dtorCount == 0);   // destructor not yet called
assert(c.s == "S");         // initial state `c.s` is `"S"`
assert(c.a.dtorCount == 0); // destructor not yet called
assert(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 called
assert(c.s == "S");         // `c.s` is back to its inital state, `"S"`
assert(c.a.dtorCount == 1); // `c.a`'s destructor was called
assert(c.a.x == 10);        // `c.a.x` is back to its inital state, `10`

// check C++ classes work too!
extern (C++) class CPP
{
    struct Agg
    {
        __gshared int dtorCount;

        int x = 10;
        ~this() { dtorCount++; }
    }

    __gshared int dtorCount;

    string s = "S";
    Agg a;
    ~this() { dtorCount++; }
}

CPP cpp = new CPP();
assert(cpp.dtorCount == 0);   // destructor not yet called
assert(cpp.s == "S");         // initial state `cpp.s` is `"S"`
assert(cpp.a.dtorCount == 0); // destructor not yet called
assert(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 initialization
assert(cpp.dtorCount == 1);   // `cpp`'s destructor was called
assert(cpp.s == "T");         // `cpp.s` is not initialized
assert(cpp.a.dtorCount == 1); // `cpp.a`'s destructor was called
assert(cpp.a.x == 30);        // `cpp.a.x` is not initialized
destroy(cpp);
assert(cpp.dtorCount == 2);   // `cpp`'s destructor was called again
assert(cpp.s == "S");         // `cpp.s` is back to its inital state, `"S"`
assert(cpp.a.dtorCount == 2); // `cpp.a`'s destructor was called again
assert(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 initialized
destroy(i);
assert(i == 0);           // `i` is back to its initial state `0`
class Object;
All D class objects inherit from Object.
string toString();
Convert Object to a human readable string.
nothrow @trusted size_t toHash();
Compute hash function for Object.
int opCmp(Object o);
Compare with another Object obj.
Returns:
this < obj < 0
this == obj 0
this > obj > 0
bool opEquals(Object o);
Test whether this is equal to o. The default implementation only compares by identity (using the is operator). Generally, overrides for opEquals should attempt to compare objects by their contents.
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.
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 !is null && c.x == 10);
}

bool opEquals(const Object lhs, const Object rhs);
Returns true if lhs and rhs are equal.
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 null
f = 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 opEquals
class F
{
    int flag;

    this(int flag)
    {
        this.flag = flag;
    }

    override bool opEquals(const Object o)
    {
        return flag == (cast(F) 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); }

    override bool opEquals(const Object o)
    {
        fEquals++;
        return flag == (cast(Base) o).flag;
    }
}

class G : Base
{
    this(int flag) { super(flag); }

    override bool opEquals(const Object o)
    {
        gEquals++;
        return flag == (cast(Base) o).flag;
    }
}

assert(new F(1) == new G(1));
assert(fEquals == 1);
assert(gEquals == 1);
struct Interface;
Information about an interface. When an object is accessed via an interface, an Interface* appears as the first entry in its vtbl.
TypeInfo_Class classinfo;
.classinfo for this interface (not for containing class)
size_t offset;
offset to Interface 'this' from Object 'this'
struct OffsetTypeInfo;
Array of pairs giving the offset and type information for each member in an aggregate.
size_t offset;
Offset of member from start of object
TypeInfo ti;
TypeInfo for this member
abstract class TypeInfo;
Runtime type information about a type. Can be retrieved for any type using a TypeidExpression.
const nothrow @trusted size_t getHash(scope const void* p);
Computes a hash of the instance of a type.
Parameters:
void* p pointer to start of instance of the type
Returns:
the hash
Bugs:
fix https://issues.dlang.org/show_bug.cgi?id=12516 e.g. by changing this to a truly safe interface.
const bool equals(in void* p1, in void* p2);
Compares two instances for equality.
const int compare(in void* p1, in void* p2);
Compares two instances for <, ==, or >.
const pure nothrow @nogc @property @safe size_t tsize();
Returns size of the type.
const void swap(void* p1, void* p2);
Swaps two instances of the type.
inout pure nothrow @nogc @property inout(TypeInfo) next();
Get TypeInfo for 'next' type, as defined by what kind of type this is, null if none.
abstract const pure nothrow @nogc @safe const(void)[] initializer();
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, use tsize to get the correct size.
const pure nothrow @nogc @property @safe uint flags();
Get flags for type: 1 means GC should scan for pointers, 2 means arg of this type is passed in XMM register
const const(OffsetTypeInfo)[] offTi();
Get type information on the contents of the type; null if not available
const void destroy(void* p);
Run the destructor on the object and all its sub-objects
const void postblit(void* p);
Run the postblit on the object and all its sub-objects
const pure nothrow @nogc @property @safe size_t talign();
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
const pure nothrow @nogc @property @safe immutable(void)* rtInfo();
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 .classinfo property.
byte[] m_init;
class static initializer (init.length gives size in bytes of class)
string name;
class name
void*[] vtbl;
virtual function pointer table
Interface[] interfaces;
interfaces this class implements
TypeInfo_Class base;
base class
static const(TypeInfo_Class) find(scope const char[] classname);
Search all modules for TypeInfo_Class corresponding to classname.
Returns:
null if not found
const Object create();
Create instance of Object represented by 'this'.
struct ModuleInfo;
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.
const pure nothrow @nogc @property void function() tlsctor();
Returns:
module constructor for thread locals, null if there isn't one
const pure nothrow @nogc @property void function() tlsdtor();
Returns:
module destructor for thread locals, null if there isn't one
const pure nothrow @nogc @property void* xgetMembers();
Returns:
address of a module's const(MemberInfo)[] getMembers(string) function, null if there isn't one
const pure nothrow @nogc @property void function() ctor();
Returns:
module constructor, null if there isn't one
const pure nothrow @nogc @property void function() dtor();
Returns:
module destructor, null if there isn't one
const pure nothrow @nogc @property void function() ictor();
Returns:
module order independent constructor, null if there isn't one
const pure nothrow @nogc @property void function() unitTest();
Returns:
address of function that runs the module's unittests, null if there isn't one
const pure nothrow @nogc @property immutable(ModuleInfo*)[] importedModules();
Returns:
array of pointers to the ModuleInfo's of modules imported by this one
const pure nothrow @nogc @property TypeInfo_Class[] localClasses();
Returns:
array of TypeInfo_Class references for classes defined in this module
const pure nothrow @nogc @property string name();
Returns:
name of module, null if no name
class Throwable;
The base class of all thrown objects.
All thrown objects must inherit from Throwable. Class Exception, 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 from Exception, 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.
string msg;
A message describing the error.
string file;
The file name of the D source code corresponding with where the error was thrown from.
size_t line;
The line number of the D source code corresponding with where the error was thrown from.
TraceInfo info;
The stack trace of where the error happened. This is an opaque object that can either be converted to string, or iterated over with foreach to extract the items in the stack trace (as strings).
inout pure nothrow @nogc @property scope @safe inout(Throwable) next() return;
Returns:
A reference to the next error in the list. This is used when a new Throwable is thrown from inside a catch block. The originally caught Exception will be chained to the new Throwable via this field.
pure nothrow @nogc @property scope @safe void next(Throwable tail);
Replace next in chain with tail. Use chainTogether instead if at all possible.
final pure nothrow @nogc ref scope @system uint refcount() 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
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);
Append e2 to chain of exceptions that starts with e1.
Parameters:
Throwable e1 start of chain (can be null)
Throwable e2 second part of chain (can be null)
Returns:
Throwable that is at the start of the chain; null if both e1 and e2 are null
string toString();
Overrides Object.toString and returns the error message. Internally this forwards to the toString overload that takes a sink delegate.
const void toString(scope void delegate(in char[]) sink);
The Throwable hierarchy uses a toString overload that takes a sink delegate to avoid GC allocations, which cannot be performed in certain error situations. Override this toString method to customize the error message.
const const(char)[] message();
Get the message describing the error. Base behavior is to return the Throwable.msg field. Override to return some other error message.
Returns:
Error message
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 a catch 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
{
    throw new Exception("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 be null when passed by user code. This constructor does not automatically throw the newly-created Exception; the throw statement should be used for that purpose.
class Error: object.Throwable;
The base class of all unrecoverable runtime errors.
This represents the category of Throwable objects that are not 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
{
    throw new Error("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 be null when passed by user code. This constructor does not automatically throw the newly-created Error; the throw statement should be used for that purpose.
Throwable bypassedException;
The first Exception which was bypassed when this Error was thrown, or null if no Exceptions were pending.
void clear(T : Value[Key], Value, Key)(T aa);
Removes all remaining keys and values from an associative array.
Parameters:
T aa The associative array.
T rehash(T : Value[Key], Value, Key)(T aa);
Reorganizes the associative array in place so that lookups are more efficient.
Parameters:
T aa The associative array.
Returns:
The rehashed associative array.
V[K] dup(T : V[K], K, V)(T aa);
Create a new associative array of the same size and copy the contents of the associative array into it.
Parameters:
T aa The associative array.
pure nothrow @nogc @safe auto byKey(T : V[K], K, V)(T aa);
Returns a forward range over the keys of the associative array.
Parameters:
T aa The associative array.
Returns:
A forward range.
pure nothrow @nogc @safe auto byValue(T : V[K], K, V)(T aa);
Returns a forward range over the values of the associative array.
Parameters:
T aa The associative array.
Returns:
A forward range.
pure nothrow @nogc @safe auto byKeyValue(T : V[K], K, V)(T aa);
Returns a forward range over the key value pairs of the associative array.
Parameters:
T aa The associative array.
Returns:
A forward range.
@property Key[] keys(T : Value[Key], Value, Key)(T aa);
Returns a dynamic array, the elements of which are the keys in the associative array.
Parameters:
T aa The associative array.
Returns:
A dynamic array.
@property Value[] values(T : Value[Key], Value, Key)(T aa);
Returns a dynamic array, the elements of which are the values in the associative array.
Parameters:
T aa The associative array.
Returns:
A dynamic array.
inout(V) get(K, V)(inout(V[K]) aa, K key, lazy inout(V) defaultValue);
Looks up key; if it exists returns corresponding value else evaluates and returns defaultValue.
Parameters:
inout(V[K]) aa The associative array.
K key The key.
inout(V) defaultValue The default value.
Returns:
The value.
ref V require(K, V)(ref V[K] aa, K key, lazy V value = V.init);
Looks up key; if it exists returns corresponding value else evaluates value, adds it to the associative array and returns it.
Parameters:
V[K] aa The associative array.
K key The key.
V value The required value.
Returns:
The value.
Examples:
auto aa = ["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));
Looks up key; if it exists applies the update callable else evaluates the create callable and adds it to the associative array
Parameters:
V[K] aa The associative array.
K key The key.
C create The callable to apply on create.
U update The callable to apply on update.
Examples:
auto aa = ["k1": 1];

aa.update("k1", {
    return -1; // create (won't be executed
}, (ref int v) {
    return v + 1; // update
});
assert(aa["k1"] == 2);

aa.update("k2", {
    return 0; // create
}, (ref int v) {
    return -1; // update (won't be executed)
});
assert(aa["k2"] == 0);
size_t hashOf(T)(auto ref T arg, size_t seed);

size_t hashOf(T)(auto ref T arg);
Calculates the hash value of arg with an optional seed initial value. The result might not be equal to typeid(T).getHash(&arg).
Parameters:
T arg argument to calculate the hash value of
size_t seed optional seed value (may be used for hash chaining)

Return calculated hash value of arg

Examples:
class MyObject
{
    size_t myMegaHash() const @safe pure nothrow
    {
        return 42;
    }
}
struct Test
{
    int a;
    string b;
    MyObject c;
    size_t toHash() const pure nothrow
    {
        size_t hash = a.hashOf();
        hash = b.hashOf(hash);
        size_t h1 = c.myMegaHash();
        hash = h1.hashOf(hash); //Mix two hash values
        return 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");