C++ Deleting Static Data

后端 未结 5 1430
难免孤独
难免孤独 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 12:07

    If the data is static, it isn't allocated on the heap, and it will be destructed during the shutdown of the process.

    If it is a pointer to the data which is static, e.g.:

    Something* MyClass::aPointer = new Something;
    

    then like all other dynamically allocated data, it will only be destructed when you delete it. There are two frequent solutions:

    • use a smart pointer, which has a destructor which deletes it, or

    • don't delete it; in most cases, there's really no reason to call the destructor, and if you happen to use the instance in the destructors of other static objects, you'll run into an order of destruction problem.

提交回复
热议问题