Satview: Pointer Perfect, Part 3 - The meaning of ownership
(Page 4 of 6 )
Because the auto_ptr forces the object it contains to have exactly one owner, this means that no two auto_ptrs should be pointing to the same object at the same time. It is up to you to make sure that this doesn’t happen.
So what happens when ownership is transferred? Look at the following example:
std::auto_ptr<MyClass> pMyObj(new MyClass);
std::auto_ptr<MyClass> pMyObj2 = pMyObj;
/*or*/
std::auto_ptr<MyClass> pMyObj3(pMyObj2);
It means that when ownership is transferred from pMyObj to pMyObj2, whatever pMyObj2 was pointing to is freed (not a big deal in this case, but what happens when you assign it another auto_ptr again?), the pointer to the resource is copied from pMyObj to pMyObj2, and pMyObj no longer points to that resource. In fact, it is pointing to NULL!
When you are using auto_ptr for making sure that resources are freed upon exiting a function, its usage is straightforward. Still, I recommend you make the object const, just to show that it is not your intention to allow its ownership to be transferred:
void foo() {
std::auto_ptr<MyClass> const pMyObj(new MyClass);
/* perform some operations here */
}
You can still make changes to the object to which the pointer contained by pMyObj refers:
pMyObj->myVar = 10;
But the const modifier prohibits you from making changes to pMyObj itself:
pMyObj = other_auto_ptr;
This way you can make it clear to other coders (who might have to maintain your code later) that the resource pMyObj contains has to be freed upon exiting this function and that its ownership is not to be transferred. Why is this important, you ask? Well, simply because the auto_ptr violates the general behavior of initializations and assignments in programming languages.
Next: The auto_ptr is counter-intuitive >>
More C# Articles
More By J. Nakamura