3

Possible Duplicate:
Is it worth setting pointers to NULL in a destructor?

I see some code like this,

void ClassA::~ClassA()
{

delete member;
member = NULL;

}

as the particular instance doesn't exist anymore after this destructor (or the instance is destructed and its members can't be used or dereferenced anymore), what is the use of assigning NULL to the pointer of member variable?

Is it just a practice taken from deleting a pointer elsewhere and assigning NULL to it?

Community
  • 1
  • 1
Sulla
  • 7,631
  • 9
  • 45
  • 71

4 Answers4

4

It's pretty pointless - the space isn't going to be used again until it is reallocated.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

It's pointless for release code, but potentially helpful for debugging.

user541686
  • 205,094
  • 128
  • 528
  • 886
0

I see no reason for updating data which is already out of scope, and it is NOT good practice to do things "just in case". At any rate do not follow "good practices" blindly, it is better to understand why you do things than being the most fervours practitioner of the "good practices" religion.

gatopeich
  • 3,287
  • 31
  • 26
-2

yes, this is just good practice. helps one not to forget to set pointers to null elsewhere ;)

davogotland
  • 2,718
  • 1
  • 15
  • 19
  • It's terrible practice. I've never, in any of my modern client (non-utility) code, set a pointer to null. This is because we shouldn't be using raw pointers to manage resources. – GManNickG Jan 12 '11 at 07:36
  • If you've written your code correctly, you shouldn't be explicitly setting pointers to `NULL` very many places at all. – James McNellis Jan 12 '11 at 07:36
  • If that reasoning holds the you are doing something horribly wrong elsewhere. – CB Bailey Jan 12 '11 at 07:38
  • @GMan you mean that instead using smart pointers from e.g. boost is better? :) – davogotland Jan 12 '11 at 07:39
  • 2
    @davogotland: Yes. From Boost or your Standard Library implementation, or from some other library (there are lots of options when it comes to smart pointers). Not using smart pointers is wrong in all but a very few use cases. – James McNellis Jan 12 '11 at 07:39
  • are the smart pointers really as fast as the raw pointers? D: – davogotland Jan 12 '11 at 07:44
  • @davot: Does it matter? Do you want a clean and working program, or a broken and fast program? But yes. They just do things you would normally do automatically. – GManNickG Jan 12 '11 at 07:49
  • @davogotland: Most sole-ownership smart pointers are (e.g. `std::auto_ptr`, `std::unique_ptr`, and `boost::scoped_ptr`). Shared-ownership smart pointers generally are not, though the performance is generally as good or better than what you would have to implement yourself to get correct shared ownership. – James McNellis Jan 12 '11 at 07:49