• Want to receive the latest contracting news and advice straight to your inbox? Sign up to the ContractorUK newsletter here. Every sign up will also be entered into a draw to WIN £100 Amazon vouchers!

C++ technical question

BlasterBates

More fingers than teeth
Joined
Jul 6, 2005
Messages
16,053
Likes received
1,667
Thanks received
471
Location
Number 10 Downing street
Given this code:

template <class T> Kill (T *& ptr)
{
delete ptr;
ptr = NULL;

};

class MyClass{};

int main()
{
MyClass* myClass = new MyClass;
Kill(myClass);
Kill(myClass);
}

What should happen here?

With my (crappy) Microsoft compiler I executed this and it destructs twice when I have *& but generates an exception when I use * instead of *& in the template definition.

Surely when the pointer is set to NULL calling delete the second time should have no effect. Why was it executed twice with *& :confused:

Is it so that the above code should just execute without error and delete the object only once?
 
Last edited: 16:08
It'll call Kill() twice, but the second time ptr is NULL and so delete ptr will do nothing. Is that what you're saying is happening?

If Kill just takes a T* then ptr=NULL is only changing the local pointer, not the original, so the second call will try to delete an object that has already been deleted, and bang.
 
Yes thx for that.

....of course a pointer to a pointer as it were.

That online compiler is very useful.

I´m using Microsoft Visual Studio C++ compiler which gives me that unexpected result of the destructor being called twice even though I set the ptr to NULL (when using *&).
 
Just tried it in VC8 for you, and the destructor is only called once. Perhaps the problem is with the other code you're not showing us?

You need a return type for the function (i.e. void) in VC8 otherwise it'll moan.
 
It´s an old Beta version of Visual Studio, which doesn´t understand NULL and so set it to 0. Anyway it works with that online compiler. Results as expected. My faith in C++ has been restored.

gr8 stuff, thx.
 

Advertisers

Back
Top