开发者

C++: is it right to delete all declarations in public and private?

I am learning C++ and I am not clear about the destructor of a class. For example:

class A:
{
  public:
    int valueA;
  private:
    int valueB;
};

A:~A()
{
  delete valueA;
  delete valueB;
}

So, basically is it开发者_JS百科 right to delete every declarations in the public and private?


No, you only need to delete that which has been allocated using new. Simple value types like ints never need to be deleted.

If your class did include data dynamically allocated using new either by the constructor or later by some other method then the destructor should typically de-allocate all of it, regardless of wether the data is public or private.

I might add that having publically visible dynamically allocated pointer members might not be the best design, though.


You can't delete ints only pointers.

Your destructor will have access to private members though so yes it could delete them if they were actually pointers (as well as the public ones).

Also just because a member of your class is a pointer, it doesn't mean your destructor is meant to delete it. C++ has a concept of "ownership". The owner is usually but not always the same as the creator (where new was called).

Note that for arrays where you use new T[x] you must use delete[].

There are automatic objects that will call delete for you. These are called smart pointers, and you should use them most of the time in preference to doing the delete manually.

A destructor may do other things other than just delete pointers. For example, if your class has attached itself to some kind of graph on creation, your destructor can automatically remove itself from that graph.


delete is only intended for pointers. In the general sense, yes, you should delete all public and private variables for which memory you own (you've reserved inside your class and it's your responsibility to delete).


No,just delete some pointers that are constructed in your class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜