Re: Deleting an Object and setting the Pointer to NULL
James Kanze wrote:
There are several very important reasons:
-- The argument for delete is not required to be an lvalue---in
fact, in my code, it often isn't. And you can't set a
non-lvalue to NULL.
-- It doesn't buy you anything, anyway, since typically,
there's not just a single pointer to the object, but a
number of them.
Those are the essential reasons, I believe.
-- Finally, most of the time when there is just a single
pointer, it is in an object, and the delete is in the
destructor, so there's no point---the pointer itself will
cease to exist.
Except when the pointer is in a container, in which case you have to
explicitly set the pointer to null to avoid undefined behaviour, IIRC:
for (i = begin(); i != end(); ++i) delete *i, *i = 0;
or
for (i = begin(); i != end(); ++i) delete i->second, i->second = 0;
In the past I've written the following to avoid repeating the same code:
template <typename T>
inline void delete_ptr(const T*& p)
{ boost::checked_delete(p); p = 0; }
template <typename T>
struct deleter : public std::unary_function<const T*&, void>
{
void operator()(const T*& p) const { delete_ptr(p); }
};
// a function object that deletes the 'second' members of std::pair's
// using member template - no need to specify the template argument
// when using, but cannot derive from std::unary_function
struct mapped_ptr_deleter
{
template <typename T1, typename T2>
void operator()(std::pair<T1, T2>& p) const { delete_ptr(p.second);}
};
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]