RAD Studio |  |

Smart Pointers (C++)

If you have local variables that are pointers to objects and an exception is thrown, these pointers are not automatically deleted. This is because there is no good way for the compiler to distinguish between a pointer to data that was allocated for this function only and any other pointer. The class that you can use to ensure that objects allocated for local use are destroyed in the even of an exception is auto_ptr. There is a special case in which memory is freed for a pointer allocated in a function:

Copy Code

    auto_ptr< TMyObject > pMyObject( new TMyObject );

In this example, if the constructor for TMyObject throws an exception, then the pointer to the object allocated for TMYObject will be deleted by the RTL when it unwinds the exception. This is the only time that the compiler automatically deletes a pointer value for you.

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!