Satview: Pointer Perfect, Part 3 - Smart pointers
(Page 3 of 6 )
It is obvious why the implementation of a garbage collector takes a lot of the worries of memory management away from you. In C++ there is another alternative--a ‘smart pointer.’ A smart pointer behaves much like a built-in pointer, except that it automatically frees resources when they are destroyed. The concept of a smart pointer is essentially simple, though the many different ways we can implement this concept provides different behaviours and leaves us with much to investigate.
When an object is declared locally in a function and thus on the stack, its destructor is automatically called when the object is thrown from the stack. If we were to create an object that can hold a built-in pointer for us, it can then call delete for us in its destructor. Our resource is automatically released and there is no need for the complex try/catch (or even worse goto) structure to make sure we are not leaking. You can see that this is as useful for freeing allocated memory as it is for guaranteeing the closure of opened files.
The smart pointers we will be looking at can be used just like the built-in pointers we have been looking at in previous articles. This means that you can use the reference and pointer-to-member operators, but you are prohibited from using the dereference and arithmetic operators. Why this is will be discussed when we look at common pitfalls when using pointers.
The Standard Library offers a smart pointer known as the auto_ptr. The auto_ptr serves as the owner of the resource it refers to and frees it automatically when it gets destroyed. Exactly the kind of thing we are looking for, right? Well there is one important caveat with the std::auto_ptr – a requirement of the std::auto_ptr is that its object can have only one owner. We will look at the consequences of this requirement, but first let’s rewrite previous example using an auto_ptr.
void foo() {
std::auto_ptr<MyClass> pMyObj(new MyClass);
/* perform some operations here */
}
There no longer is a need to worry about memory leaks in the face of exceptions, and we can even forget about including the delete statement! Great, isn’t it? Note that you can only initialise smart pointers through the constructor; the assignment operator has been reserved to only work with objects of the same (smart pointer) class, making the following statement invalid:
std::auto_ptr<MyClass> pMyObj = new MyClass;
Next: The meaning of ownership >>
More C# Articles
More By J. Nakamura