View source code
							
							
						
								Display the source code in object.d from which this
								page was generated on github.
							
						
							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
								local clone.
							
						Function object.destroy
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.
						
				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));
						
					
				Example
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(cExample
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(cppExample
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`
Example
Nested struct type
int dtorCount;
struct A
{
    int i;
    ~this()
    {
        dtorCount++; // capture local variable
    }
}
A a = A(5);
destroy!false(a);
writeln(dtorCount); // 1
writeln(aAuthors
Walter Bright, Sean Kelly
License
					Copyright © 1999-2024 by the D Language Foundation | Page generated by ddox.