Do I need to invalidate a member variable in a destructor?

Why would it be necessary to explicitly clear a member variable of a vector (from to dtor (see the code below). What are the advantages of cleaning a vector, although it will be destroyed immediately after the last line? Dtor code will be executed?

class A { ~A() { values.clear(); } private: std::vector < double > values_; }; 

similar question about the following code:

 class B { ~B() { if (NULL != p) { delete p_; p_ = NULL; } } private: A * p_; }; 

Since there is no way to call dtor twice, why reset p_ then?

+6
c ++
source share
3 answers

In class A there is no reason for the .clear() member variable vector -type in the destructor. The vector destructor will be .clear() vector when it is called.

In class B the cleanup code can simply be written as:

 delete p_; 

There is no need to check if p_ != NULL first, because delete NULL; defined as no-op. There is also no need to set p_ = NULL after you delete d, because p_ can no longer be legally accessible after the destruction of the object of which it is a member.

However, you rarely need to use delete in C ++ code. You should prefer to use visibility-limited resource management (SBRM, also called resource acquisition initialization) to automatically manage resource resource timing.

In this case, you can use the smart pointer. boost::scoped_ptr and std::unique_ptr (from C ++ 0x) are a good choice. None of them should have an overhead compared to using an unprocessed pointer. In addition, they both suppress the generation of the implicitly declared copy constructor and copy assignment operator, which you usually want when you have a member variable that is a pointer to a dynamically allocated object.

+11
source share

In your second example, there is no reason to set p_ to zero, especially because it is done in the destructor, which means that the lifetime of p_ will end right after that.

In addition, it makes no sense to compare p_ with null before calling delete , since the delete performs this check internally. In your specific artificial example, the destructor should just contain delete p_ and note another. No if , without setting p_ to null.

+2
source share

In the case of p_, there is no need to set it equal to zero in the destructor, but it can be a useful defense mechanism. Imagine a case where you have an error and something else holds a pointer to object B after it is deleted:

If he tries to delete object B, p_ will be empty, this will lead to the fact that the second removal will be harmless, and not a heap of corruption.

If he tries to call a method in a B object, p_ will be null, this will crash right away. If p_ is still the old value, the results are undefined, and it can be difficult to track down the cause of the failure.

0
source share

All Articles