Friday, December 31, 2010

Delete Pointer Passed to Function C++ Parameter

I hate C++ pointers. I switch from C to C++ to Java a lot, so I tend to need refreshing once in a while when I go from Java to C++.
I was updating some old code the other day and came across a function which was supposed to delete a pointer passed to it and then set it to null. When the function returned, the pointer was deleted, but was not null. Reason why: the function had been set up wrong:

void deletePointer(XYZ* _xyz)
{
delete _xyz;
_xyz = 0;
}


void callDeletePointer()
{
XYZ* xyz = new XYZ();
...
...
...
deletePointer(xyz);
}

The way deletePointer really needed to be set up is like this:

void deletePointer(XYZ*& _xyz)
{
delete _xyz;
_xyz = 0;
}

Here's why:
The first deletePointer receives a copy of the pointer to _xyz, which allows the user to modify the object addressed by the pointer.
The second deletePointer receives the actual pointer to _xyz, which allows the user to modify the pointer itself.

Oh and one more tip:
When deallocating memory do this:

XYZ* xyz = new XYZ();
delete xyz;
xyz = 0;

instead of:

XYZ* xyz = new XYZ();
if(xyz != 0)
{
delete xyz;
xyz = 0;
}


Apparently, C++ guarantees operator delete() won't be called by a delete if the pointer is 0, so testing for null is not necessary. In fact, if you do include a pointer null test, the test will be done twice.

Source: C++ Primer, Third Edition, by Stanley B. Lippman, Josee Lajoie


More C++


No comments: