Destructor (computer programming)

Last updated

In object-oriented programming, a destructor (sometimes abbreviated dtor [1] ) is a method which is invoked mechanically just before the memory of the object is released. [2] It can happen either when its lifetime is bound to scope and the execution leaves the scope, when it is embedded in another object whose lifetime ends, or when it was allocated dynamically and is released explicitly. Its main purpose is to free the resources (memory allocations, open files or sockets, database connections, resource locks, etc.) which were acquired by the object during its life and/or deregister from other entities which may keep references to it. Destructors are necessary in resource acquisition is initialization (RAII).

Contents

With most kinds of automatic garbage collection algorithms, the releasing of memory may happen a long time after the object becomes unreachable, making destructors unsuitable for time-critical purposes. In these languages, the freeing of resources is done through an lexical construct (such as try-finally, Python's with, or Java's "try-with-resources"), or by explicitly calling a function (equivalent to explicit deletion); in particular, many object-oriented languages use the dispose pattern.

Syntax

Language details

C++

The destructor has the same name as the class, but with a tilde (~) before it. [2] For example, a class called Foo will have the destructor ~Foo(). Additionally, destructors have neither parameters nor return types. [2] As stated above, a destructor for an object is called whenever the object's lifetime ends. [2] If the object was created as an automatic variable, its lifetime ends and the destructor is called automatically when the object goes out of scope. Because C++ does not have garbage collection, if the object was created with a new statement (dynamically on the heap), then its destructor is called when the delete operator is applied to a pointer to the object. Usually that operation occurs within another destructor, typically the destructor of a smart pointer object.

In inheritance hierarchies, the declaration of a virtual destructor in the base class ensures that the destructors of derived classes are invoked properly when an object is deleted through a pointer-to-base-class. Objects that may be deleted in this way need to inherit a virtual destructor.

A destructor should never throw an exception. [8]

Non-class scalar types have what's called a pseudo-destructor which can be accessed by using typedef or template arguments. This construct makes it possible to write code without having to know if a destructor exists for a given type.

intf(){inta=123;usingT=int;a.~T();returna;// undefined behavior}

In older versions of the standard, pseudo-destructors were specified to have no effect, however that was changed in a defect report to make them end the lifetime of the object they are called on. [9]

Objects which cannot be safely copied and/or assigned should be disabled from such semantics by declaring their corresponding functions as deleted. A detailed description of this method can be found in Scott Meyers' popular book, Effective Modern C++ (Item 11: "Prefer deleted functions to private undefined ones." [10] ). If they are marked deleted, they should be public so that accidental uses do not warn that they are private, but explicitly deleted. Since C++26, it is possible to specify a reason for the deletion.

Example

importstd;classFoo{private:chardata[];friendstructstd::formatter<Foo>;public:// ConstructorexplicitFoo(constchar*s=""):data{newchar[std::strlen(s)+1]}{std::strcpy(data,s);}Foo(constFoo&other)=delete("Copy construction disabled");Foo&operator=(constFoo&other)=delete("Copy assignment disabled");// Destructor~Foo(){delete[]data;}};template<>structstd::formatter<Foo>{constexprautoparse(std::format_parse_context&ctx)->constchar*{returnctx.end();}template<typenameFormatContext>autoformat(constFoo&foo,FormatContext&ctx)->FormatContext::iterator{returnstd::format_to(ctx.out(),"{}",foo.data);}};intmain(intargc,char*argv[]){Foofoo("Hello from the stack!");std::println("{}",foo);Foo*foo=newFoo("Hello from the heap!");std::println("{}",*foo);deletefoo;}

By using smart pointers with the "Resource Acquisition is Initialization" (RAII) idiom, manually defining destructors or calling resource cleanup can be bypassed. Other languages like Java and C# include a finally block for cleanup, however C++ does not have the finally block and instead encourages using the RAII idiom.

importstd;classFoo{private:std::unique_ptr<char[]>data;friendstructstd::formatter<Foo>;public:// ConstructorexplicitFoo(constchar*s=""):data{std::make_unique<char[]>(std::strlen(s)+1)}{std::strcpy(data.get(),s);}Foo(constFoo&other)=delete("Copy construction disabled");Foo&operator=(constFoo&other)=delete("Copy assignment disabled");// Destructor is automatically handled by unique_ptr~Foo()=default;};template<>structstd::formatter<Foo>{constexprautoparse(std::format_parse_context&ctx)->constchar*{returnctx.end();}template<typenameFormatContext>autoformat(constFoo&foo,FormatContext&ctx)->FormatContext::iterator{returnstd::format_to(ctx.out(),"{}",foo.data.get());}};intmain(intargc,char*argv[]){Foofoo("Hello from the stack!");std::println("{}",foo);std::unique_ptr<Foo>foo=std::make_unique<Foo>("Hello from the heap!");std::println("{}",*foo);}

C#

Destructors in C# are not manually called or called by a delete operator like in C++. They are only called by the garbage collector.

UML class in C# containing a constructor and a destructor. Csharp finalizer.svg
UML class in C# containing a constructor and a destructor.
usingSystem;classMyClass{privatestringresource;publicMyClass(stringresourceName){resource=resourceName;}~MyClass(){Console.WriteLine($"Destructor called to clean up resource: {resource}");// cleanup code}}classProgram{staticvoidMain(string[]args){MyClassobj=newMyClass("Sample Resource");GC.Collect();GC.WaitForPendingFinalizers();Console.WriteLine("Program finished");}}

C# also has a "dispose" pattern in which the class must implement the interface IDisposable. C# supports try-with-resources blocks similar to Java, called using-with-resources. A class must implement IDisposable to be used in a using-with-resources block.

usingSystem;classMyClass:IDisposable{privatestringresource;privatebooldisposed=false;// To detect redundant calls to Dispose()publicMyClass(stringresourceName){resource=resourceName;}~MyClass(){Console.WriteLine("Destructor called");Dispose(false);}publicvoidDispose(){Console.WriteLine("Disposer called");Dispose(true);GC.SuppressFinalize(this);}protectedvirtualvoidDispose(booldisposing){if(!disposed){if(disposing){Console.WriteLine("Disposing managed resources.");}Console.WriteLine("Disposing unmanaged resources.");disposed=true;}}}classProgram{staticvoidMain(string[]args){using(Destructibled=newDestructible()){Console.WriteLine("Using Destructible.");// ...}// after using-with-resources, d.Dispose() will be called}}

C with GCC extensions

The GNU Compiler Collection's C compiler comes with 2 extensions that allow implementing destructors:

Java

Java provides 2 interfaces that implement destructors, java.lang.Closeable (deprecated) and java.lang.AutoCloseable. A class that implements AutoCloseable is able to be used in a "try-with-resources" block, available since Java 7. [13]

finalclassDestructibleimplementsAutoCloseable{@Overridepublicvoidclose(){// cleanup code }}publicfinalclassExample{try(Destructibled=newDestructible()){System.out.println("Using Destructible.");// ...}// after try-with-resources, d.close() will be called}

Prior to Java 7, a "try-finally" block was used.

finalclassDestructible{publicvoidclose(){// cleanup code}}publicfinalclassExample{try{Destructibled=newDestructible();System.out.println("Using Destructible.");}finally{d.close()}}

Historically, Java used Object.finalize() instead, however this has been deprecated. Java has a method called System.gc() to suggest the Java Virtual Machine (JVM) to perform garbage collection, which internally calls Runtime.getRuntime().gc(), which requests the garbage collector to trigger a garbage collection cycle, but this is not guaranteed, as the JVM manages memory independently. System.gc() may lead to finalize() being called, but only if the object is eligible for garbage collection and has a finalize() method.

classParentFinalizerExample{...}classFinalizerExampleextendsParentFinalizerExample{@Overrideprotectedvoidfinalize()throwsThrowable{try{System.out.println("finalize() called, cleaning up...");}finally{super.finalize();// Always call super.finalize() to clean parent classes}}}publicclassExample{publicstaticvoidmain(String[]args){FinalizerExampleobj=newFinalizerExample();obj=null;System.gc();// Requests garbage collection (not guaranteed)}}

Java also supports classes java.lang.ref.Cleaner and java.lang.ref.PhantomReference for safer low-level cleanup. Cleaner was introduced in Java 9 and is more efficient than PhantomReference, and works by registering an object with a cleaner thread which runs a cleanup action once the object is unreachable (i.e. no references to it exist).

importjava.lang.ref.Cleaner;importjava.lang.ref.Cleaner.Cleanable;classResource{privatestaticfinalCleanercleaner=Cleaner.create();staticclassStateimplementsRunnable{privatebooleancleaned=false;@Overridepublicvoidrun(){cleaned=true;System.out.println("Cleaned using Cleaner");}}privatefinalStatestate;privatefinalCleanablecleanable;publicResource(){this.state=newState();this.cleanable=cleaner.register(this,state);}publicvoidcleanup(){System.gc();// Request garbage collection (not guaranteed)}}publicclassExample{publicstaticvoidmain(String[]args){Resourceresource=newResource();resource=null;resource.cleanup();}}

PhantomReference, since Java 1.2, is an older cleanup mechanism that uses a reference queue. PhantomReference is used solely for being notified that an object's garbage collection is pending. Once the object is garbage collected, the PhantomReference is enqueued into the ReferenceQueue. Unlike WeakReference which can be used to access the object if it still exists in memory, PhantomReference can only be used for detecting when an object will be destroyed. Both PhantomReference and WeakReference do not increase reference counts.

importjava.lang.ref.PhantomReference;importjava.lang.ref.ReferenceQueue;classResource{privatefinalStringname;publicResource(Stringname){this.name=name;}publicStringgetName(){returnname;}}publicclassPhantomReferenceExample{publicstaticvoidmain(String[]args)throwsInterruptedException{Resourceresource=newResource("My resource");ReferenceQueue<Resource>queue=newReferenceQueue<>();PhantomReference<Resource>phantomRef=newPhantomReference<>(resource,queue);resource=null;System.gc();Reference<?extendsResource>ref=queue.poll();if(ref!=null){System.out.printf("Object is ready to be collected: %s%n",((PhantomReference<?>)ref).get());}}}

Unlike to std::weak_ptr in C++ which is used to reference an object without increasing its reference count, WeakReference can still access the object after the reference count reaches 0, whereas in C++ std::weak_ptr cannot as the object is immediately destroyed once the object reaches 0 references.

Python

Python supports destructors and has a del keyword, but unlike delete in C++, del only decreases the reference count of the object, and does not necessarily immediately destroy the object.

classDestructible:def__init__(self,name:str)->'Destructible':self.name=nameprint(f"Created Destructible: {self.name}")def__del__(self)->None:print(f"Destructor called for: {self.name}")if__name__=="__main__":d:Destructible=Destructible("My name")print(f"Using Destructible: {d.name}")deld

Much like Java and C#, Python has a try-with-resources block, called a with block or a "context manager". It is used for things like files and network connections.

fromtypingimportOptionalclassDestructible:def__init__(self,name:str)->None:self.name:str=namedef__enter__(self)->"Destructible":print(f"Entering context (allocating resource: {self.name})")returnselfdef__exit__(self,exc_type:Optional[type],exc_val:Optional[Exception]None,exc_tb:Optional[type])->None:print(f"Exiting context (cleaning up resource: {self.name})")if__name__=="__main__":withDestructible("Resource A")asd:print(f"Using resource {d.name} inside context")# Most Python standard library resources support with blocks:withopen(file_path,"r")asfile:print("Reading the file content:")content:str=file.read()print(content)

Rust

Rust does not have destructors in the sense of object-oriented programming, but a struct can implement the Drop trait and the drop method to clean itself up after it goes out of scope.

It is not possible to destroy objects explicitly through a delete operator like in C++, though it is possible to manually call drop() prematurely by using std::mem::drop().

usestd::mem;structDestructible{name:String,}implDestructible{fnnew(name:String)->Self{Destructible{name}}}implDropforDestructible{fndrop(&mutself){println!("Dropping Destructible: {}",self.name);}}fnmain(){{letresource_a:Destructible=Destructible::new(String::from("Resource A"));println!("Using Destructible.");}// <--- resource_a goes out of scope here, `drop()` is called automaticallyletresource_b:Destructible=Destructible::new(String::from("Resource B"));println!("Dropping Destructible prematurely.");mem::drop(resource_b);}

While lifetimes control the validity of references, they do not determine when drop() is called.

Xojo

Destructors in Xojo (REALbasic) can be in one of two forms. Each form uses a regular method declaration with a special name (with no parameters and no return value). The older form uses the same name as the Class with a ~ (tilde) prefix. The newer form uses the name Destructor. The newer form is preferred because it makes refactoring the class easier.

Class Foobar   // Old form   Sub ~Foobar()   End Sub    // New form   Sub Destructor()   End Sub End Class

See also

References

  1. "dtor". TheFreeDictionary.com. Retrieved 2018-10-14.
  2. 1 2 3 4 5 Sebesta, Robert W. (2012). ""11.4.2.3 Constructors and Destructors"". Concepts of Programming Languages (print) (10th ed.). Boston, MA, USA: Addison-Wesley. p. 487. ISBN   978-0-13-139531-2.
  3. "Finalizers (C# Programming Guide)".
  4. Constructors and Destructors, from PHP online documentation
  5. "3. Data model — Python 2.7.18 documentation".
  6. "3. Data model — Python 3.10.4 documentation".
  7. "Destructors - the Rust Reference".
  8. GotW #47: Uncaught exceptions Accessed 31 July 2011.
  9. Smith, Richard; Voutilainen, Ville. "P0593R6:Implicit creation of objects for low-level object manipulation". open-std.org. Retrieved 2022-11-25.
  10. Scott Meyers: Effective Modern C++, O'REILLY, ISBN   9781491903995
  11. C "destructor" function attribute
  12. Erickson, Jon (2008). Hacking the art of exploitation. No Starch Press. ISBN   978-1-59327-144-2.
  13. Bloch, Joshua (2018). Effective Java (3rd ed.). Addison-Wesley. pp. 29–31. ISBN   978-0134685991.