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 it will be destroyed just after the last line of dtor code will get executed?
class A
{
~A()
{
values.clear();
}
private:
std::vector < double > values_;
};
similar question about a the following code:
class B
{
~B()
{
if (NULL != p)
{
delete p_;
p_ = NULL;
}
}
private:
A * p_;
};
Since there is no way the dtor will get called twice, why to nullify p_ then?
In class
A, there is absolutely no reason to.clear()thevector-type member variable in the destructor. Thevectordestructor will.clear()thevectorwhen it is called.In class
B, the cleanup code can simply be written as:There is no need to test whether
p_ != NULLfirst becausedelete NULL;is defined to be a no-op. There is also no need to setp_ = NULLafter you’vedeleted it becausep_can no longer be legitimately accessed after the object of which it is a member is destroyed.That said, you should rarely need to use
deletein C++ code. You should prefer to use Scope-Bound Resource Management (SBRM, also called Resource Acquisition Is Initialization) to manage resource lifetimes automatically.In this case, you could use a smart pointer.
boost::scoped_ptrandstd::unique_ptr(from C++0x) are both good choices. Neither of them should have any overhead compared to using a raw pointer. In addition, they both suppress generation of the implicitly declared copy constructor and copy assignment operator, which is usually what you want when you have a member variable that is a pointer to a dynamically allocated object.