-1

Consider the following code:

template<class T> void Kill(T *& objPtr)
{
   delete objPtr;
   objPtr = NULL;
}
class MyClass
{
};
void Test()
{
   MyClass *ptr = new MyClass();
   Kill(ptr);
   Kill(ptr);
} 

Invoking Test() will cause which of the following?

Answer: Code will Crash or Throw and Exception

Test answer is wrong yes? It will not crash as we delete NULL pointer which is safe.

Narek
  • 38,779
  • 79
  • 233
  • 389
  • You're correct. I'd guess the test answer was originally written assuming the pointer was passed by value, not reference (or, it was just written by somebody who didn't know what they were doing). – Jerry Coffin Aug 16 '14 at 04:52
  • 2
    The definition of `NULL` is not shown, and it just *could* be something ridiculous instead of standard `NULL`. Without this one can only say that it's very *likely* (but not proved) that the test answer is incorrect. – Cheers and hth. - Alf Aug 16 '14 at 04:53

2 Answers2

3

You are correct, the test answer is wrong.

The first Kill calls delete, and set the pointer (passed by reference) to NULL The second Kill calls delete on a null pointer, which is safe.

Note:

As per Cheers and hth. - Alf commented, this is assuming NULL is the usual null pointer, 0.

Community
  • 1
  • 1
quantdev
  • 23,517
  • 5
  • 55
  • 88
2

Yes it is safe to delete a null pointer however I dont think you need to call the delete twice as delete performs the check anyway. Also I would recommend you to use use smart pointers like unique_ptr<T> which take care of deletion.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331