Practical application of class destructor

社会主义新天地 提交于 2019-12-03 21:23:38

问题


I'm currently trying to learn about classes and constructors/destructors. I understand what the two do, but I'm having a harder time with the destructors because I can't think of a practical application for its use.

Can anyone provide an example with an explanation?


回答1:


Destructors are special member functions used to release any resources allocated by the object.

The most common example is when the constructor of the class uses new, and the destructor uses delete to deallocate the memory.

class Myclass
{
    int *m_ptr;
    public:
        Myclass():m_ptr(new int)
        {
        }
        ~Myclass()
        {
             delete m_ptr;
        }
        //ToDo: Follow Rule of Three
        //Provide definitions for copy constructor & copy assignment operator as well

};



回答2:


Destructors are probably the most important aspect of c++, it manages resources for you and allows you add code to handle any special cleanup such as handle deallocation, disconnections from sockets, DB's etc.. Bjarne Stroustup also states that this is one of the nice things about destructors:

There have also been positive surprises. The most spectacular has been the pervasive use of destructors in techniques relating to resource management and error handling (using exceptions). I knew destructors were a good idea—after all, you have to reverse the effect of a constructor—but I didn't realize quite how central they would be to good use of C++.

Original article: http://msdn.microsoft.com/en-us/magazine/cc500572.aspx

It is also essential to the idiom RAII (Resource Acquisition Is Initialisation) and explained by Bjarne in this article: http://www.artima.com/intv/modern3.html

You can read this C++ faq on destructors which should help you even more.

I think Als code sample is a fine example, you can also look at the code sample in the wikipedia article which is also another example. The fact that the destructor is called when the object goes out of scope or when delete is called is very useful. Something I use is a timer object class to time how long certain function calls take:

class myTimer
{
  mytimer():startTime( TimeNow() )
  {}
  ~myTimer()
  { 
    printf("time taken :%I64d", TimeNow() - startTime);
  }
private:
  __int64 startTime;
};

so in my code I would do something like this

myClass::myFunction()
{
  myTimer timer; // initiliases time to Now.

  someOtherFunc();
} // mytimer object is now out of scope and the destructor is called and prints the time it took



回答3:


Imagine you have a class for file operations, e.g. ifstream and you like that this file is closed automaticly the instance of the class go away. Put a close on the file handle in the desctructor.




回答4:


these have the most power when you have composition of dynamically allocated objects

say that I am making linkedList structure that holds pointers to linkedListNodes the list will hold the pointers to the first, and depending on singly, or doubly the last element.

in the destructor I would place the removal of all elements in the list, and therefore the list itself.

If I do not code the destructor then when the list goes out of scope, or has delete called on it the memory that was allocated for those elements is lost, and cannot be reclaimed by the system (most notably called a memory leak)




回答5:


Constructors and Destructors are very important pieces of the RAII (Resource Allocation Is Initialization) idiom. Linking the acquisition of resources (files, memory, sockets, other class objects) to the lifetime of an object is a very powerful tool. When an object goes out of scope, either through normal execution or due to an exception, having the object destructor called allows the class to clean up its resources properly, without having to burden the code using an object with lots of extra finalization steps.




回答6:


Extending @Als's answer here, for example you have a class,

class A {
    B* ptrB; // B is another class / struct / internal type
    A() { ptrB = new B(); }
}

int main() {
    A* ptrA = new A();
    // Do something with A
    delete ptrA; // This does not free ptrA->ptrB
}

To take care of this problem, declare a destructor in A as follows,

~A() { delete ptrB; } // This is called every time delete is called on
                      // an object of A


来源:https://stackoverflow.com/questions/10310513/practical-application-of-class-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!