Do I need to nullify a member variable in the destructor?

后端 未结 3 1749
我在风中等你
我在风中等你 2021-01-18 11:19

Why one would want to explicitly clear the a vector member variable (of on in a dtor (please see the code below). what are the benefits of clearing the vector, even though i

3条回答
  •  孤城傲影
    2021-01-18 11:31

    In the case of p_, there is no need to set it equal to null in the destructor, but it can be a useful defensive mechanism. Imagine a case where you have a bug and something still holds a pointer to a B object after it has been deleted:

    If it trys to delete the B object, p_ being null will cause that second delete to be innocuous rather than a heap corruptor.

    If it trys to call a method on the B object, p_ being null will cause a crash immediately. If p_ is still the old value, the results are undefined and it may be hard to track down the cause of the resulting crash.

提交回复
热议问题