views:

284

answers:

1

Hello all,

I want to delete a 2 level derived class with a function and putting its handle to null. A piece of code will be helpfull:

ref class bob
{
};

ref class bill : public bob
{
};

ref class jack : public bill
{
};

void DeleteX( bob ^% x )
{
  if( x != nullptr )
  {
    delete x;
    x = nullptr;
  }
}

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
  bill^ one = gcnew jack();
  DeleteX(one);
  System::Diagnostics::Trace::Assert(one == nullptr); //Failed
  return 0;
}

If I use the same type for my declaration and for my function argument, it works. But I want to use the middle type for my declaration and the upper type for the function argument. How can I do this please ?

This is the solution I finally use:

template<class T>
void DeleteX( T ^% x )
{
  if( x != nullptr )
  {
    delete x;
    x = nullptr;
  }
}
+1  A: 

It just works for me...

ref class bob
{
};

ref class bill : public bob
{
};

void DeleteX( bob ^% x )
{
  if( x != nullptr )
  {
    delete x;
    x = nullptr;
  }
}

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    bob^ one = gcnew bill();
    DeleteX(one);
    System::Diagnostics::Trace::Assert(one == nullptr); //did not trigger
demoncodemonkey
I just tried your small example and it works for me too. But it doesn't work apply to my full code. I searched where is the difference and it is in an extra derivation.I modified my question to include that.Thanks.
Jyhess
Because the function expects a 'bob', and you pass it a 'bill', it has to cast the bill to a temporary bob object. The temporary object gets set to null by the function, however this does not affect the original bill object. Wow if that braindump makes any sense I'd be very surprised :)
demoncodemonkey
Yes I arrived to the same conclusion. To bypass this problem, I templetize the function DeleteX: template<class T> void DeleteX( T ^% x )I'm going to add this solution at the end of the question for a better visibility.Thanks for your help.
Jyhess