When do I need to declare my own destructor?

前端 未结 6 839
时光取名叫无心
时光取名叫无心 2020-12-31 05:00
class Point    
{
public:
    float x,y;
    Point() {}
    Point(float,float);
    Point operator + (Point);
    Point operator * (double);
    void rotate_p(float)         


        
6条回答
  •  再見小時候
    2020-12-31 05:30

    • Although if you don't define one, the language will define a destructor for you.

    • Generally, is a good idea to define your destructor as virtual, in order to assure that things will be OK if someone inherits from your class.

    • However, it is mandatory to define your destructor if you allocate dynamically memory in your constructors, and make sure that any allocated memory will be deleted in it, in order to avoid memory leaks.

    • Another suggestion is that if your compiler supports C++11 features, it would be for the best to avoid raw pointers for your memory allocations and use smart pointers (i.e., RAII). Thus, you will not have to delete any previously allocated memory in your destructors.

提交回复
热议问题