Destructor (computer programming)

Destructor (computer programming)

In object-oriented programming, a destructor (sometimes shortened to dtor) is a method which is automatically invoked when the object is destroyed. Its main purpose is to clean up and to free the resources (which includes closing database connections, releasing network resources, relinquishing resource locks, etc.) which were acquired by the object along its life cycle and unlink it from other objects or resources invalidating any references in the process. The use of destructors is key to the concept of Resource Acquisition Is Initialization (RAII).

In binary programs compiled with the GNU C Compiler, special table sections called .dtors are made for destructors. This table contains an array of addresses to the relevant functions that are called when the main() function exits.[1] A function can be declared as a destructor function by definining the destructor attribute __attribute__ ((destructor)) for a static function

In a language with an automatic garbage collection mechanism, it would be difficult to deterministically ensure the invocation of a destructor, and hence these languages are generally considered unsuitable for RAII. In such languages, unlinking an object from existing resources must be done by an explicit call of an appropriate function (usually called Dispose()). This method is also recommended for freeing resources rather than using finalizers for that.

Contents

Destructor syntax

  • C++ has the naming convention in which destructors have the same name as the class of which they are associated with, but prefixed with a tilde (~).
  • In Object Pascal, destructors have the keyword "destructor" and can have user-defined names (but are mostly called "Destroy").
  • In Perl, the destructor method is named DESTROY.
  • In Moose object system for Perl, the destructor method is named DEMOLISH.
  • In Objective-C, the destructor method is named "dealloc".
  • In PHP 5, the destructor method is named "__destruct". There were no destructors in previous versions of PHP.[2]

In C++

The destructor has the same name as the class, but with a tilde (~) in front of it. If the object was created as an automatic variable, its destructor is automatically called when it goes out of scope. If the object was created with a new expression, 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.[3]

Example

#include <iostream>
#include <string>
 
class foo
{
        public:
 
        foo( void )
        { 
                print( "foo()" );
        } 
 
        ~foo( void )
        { 
                print( "~foo()" );
        }
 
        void print( std::string const& text ) 
        {
                std::cout << static_cast< void* >( this ) << " : " << text << std::endl;
        }
 
/* 
        Disable copy-constructor and assignment operator by making them private
*/ 
        private:
 
        foo( foo const& );
 
        foo& operator = ( foo const& );
};
 
int main( void )
{
        foo array[ 3 ];
/* 
        When 'main' terminates, the destructor is invoked for each element 
        in 'array' (the first object created is last to be destroyed)
*/
}

Objects which cannot be safely copied should be disabled from such semantics by declaring their corresponding functions within a non-public encapsulation level (in the above example, "private"). A detailed description of this technique can be found in Scott Meyers' popular book, Effective C++ (Item 6: "Explicitly disallow the use of compiler-generated functions you do not want."[4]).

In C with GCC extensions

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

  • the "destructor" function attribute allows to define global prioritized destructor functions: when main() returns, these functions are called in priority order before the process terminates;
  • the "cleanup" variable attribute allows to attach a destructor function to a variable: the function is called when the variable goes out of scope.

REALbasic

Destructors in 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 itself with a ~ (tilde) prefix. The newer form uses the name "Destructor". The newer form is the preferred one 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. ^ Erickson, Jon (2008). Hacking the art of exploitation. No Starch Press. ISBN 1-59327-144-1. 
  2. ^ Constructors and Destructors, from PHP online documentation
  3. ^ GotW #47: Uncaught exceptions Accessed 31 July 2011.
  4. ^ Scott Meyers: Effective C++, Addison-Wesley, ISBN 0-321-33487-6

Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать реферат

Look at other dictionaries:

  • Destructor (computer science) — In object oriented programming, a destructor (sometimes shortened to dtor) is a method which is automatically invoked when the object is destroyed. Its main purpose is to clean up and to free the resources which were acquired by the object along… …   Wikipedia

  • Method (computer programming) — In object oriented programming, a method is a subroutine (or procedure or function) associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time. Methods have the special property… …   Wikipedia

  • Destructor — may refer to: Destructor (computer science), in object oriented programming, a method which is automatically invoked when an object is destroyed. Euronymous (1968 1993), guitarist and co founder of the Norwegian black metal band Mayhem. Spanish… …   Wikipedia

  • Constructor (object-oriented programming) — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Comparison of programming languages (object-oriented programming) — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Swap (computer science) — For other uses of swap , see swap (disambiguation). In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory. For example, in a program,… …   Wikipedia

  • Class (computer science) — In object oriented programming, a class is a programming language construct that is used as a blueprint to create objects. This blueprint includes attributes and methods that the created objects all share.More technically, a class is a cohesive… …   Wikipedia

  • Method (computer science) — In object oriented programming, the term method refers to a subroutine that is exclusively associated either with a class (called class methods, static methods, or factory methods) or with an object (called instance methods). Like a procedure in… …   Wikipedia

  • Clarion (programming language) — For other uses, see Clarion. Clarion Developer(s) JPI, Clarion International, SoftVelocity Stable release 8.0 / August 30, 2011; 2 months ago (2011 08 30) Operating system …   Wikipedia

  • List of object-oriented programming terms — Those words found in object oriented programming. Some are related to OOP and some not. A * Abstract class (also called deferred class) * Abstract method * Abstraction (computer science) * Access control * Accessor method * Allocated class *… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”