C++ Deleting Static Data

后端 未结 5 1434
难免孤独
难免孤独 2021-02-12 11:47

If I have a class that contains private static data allocated on the heap that never changes, when, if at all, should I delete it?

As I understand it, a class itself is

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-12 11:54

    I presume you're actually referring to a static pointer to an object on the heap?

    This will never be deleted automatically, you must do it yourself. Most of the time it's sufficient to let the program end and the OS do the cleanup, unless you're using a memory checking tool or the destructor has side effects that you require.

    The easiest thing to do is use a smart pointer, which will automatically delete the object when nobody is referring to it anymore. You can keep a copy of the pointer in main if there are times when nobody will have a copy, then the object will be deleted when main exits.

提交回复
热议问题