Topic : Deleting Pointers
Author : Yordan Gyurchev
Page : << Previous 2  
Go to page :


of the new/delete sequence thus leaving place for fewer errors.

Smart pointer can be used with STL containers as well (this is not the case with STL auto_ptr [2]). For more detailed discussion on smart pointers see “More Effective C++” Item 28. [1]. Used with STL containers smart pointers prevent us from another headache. Look at this piece of code:

void main()
{
    vector<int*> vec;
    vec.push_back(new int(1));
    vec.push_back(new int(2));

    throw some_exception;

    for_each(vec.begin(), vec.end(), SafeDeletor());
}

 
We have a memory leak here, because the vector object will be destroyed but the pointers will stay allocated. On other hand if there were smart pointers the destruction of the container would delete the pointers as well.

For a good smart pointer implementations refer to the libraries at boost.org. [5]

Pointers to Arrays
There is one additional form of new and delete operators – the form that handles arrays of objects. A call to new[] operators should be paired with a corresponding delete [] operator. Failure to do so will result in indefinite behavior. Even for built in types the result is still undefined. You may feel secure writing the following code:

int* pint_array = new int[100];
delete pint_array; //WRONG


But this is totally false security. The rule is: use the exact type of delete operator that corresponds to the new operator used to create the object.

What can we do:
1. Use another SafeDeleteArray function for arrays that employs the delete [] operator
2. Use another SafeDeletetorArray functional object though if you refer to [2] you will find that there is hardly any point in doing that
3. Use another SmartPointer to wrap around array pointers

Conclusion
Now you know (or probably you have already known) how to write a SafeDelete function.

The SafeDelete is good programming “weapon” but really looses sense with more advanced resource and memory techniques. Bad memory and resource management design is always hatchery of many bugs and leaks and even an excellent SafeDelete function won’t help you a lot if you missed this part of design.


Bibliography
1. Scott Meyers; Effective C++, More Effective C++
2. Scott Meyers; Effective STL
3. Herb Sutter; C/C++ Users Journal (11/2000), Exceptions thrown during object construction must be handled with extreme care.
4. Klaus Kreft, Angelika Langer; C/C++ Users Journal (2/2001), Effective Standard C++ Library: for_each vs. transform
5. Boost.org (www.boost.org)





Page : << Previous 2