Satview: Pointer Perfect, Part 3 - The auto_ptr is counter-intuitive
(Page 5 of 6 )
Because of the requirement that there can be only one owner of a resource when using the auto_ptr, the copy constructor of an auto_ptr modifies the object that is used to initialize the new object, and the assignment operator modifies the right-hand side of the assignment. Yes, you read that right! It is up to you to make sure that the auto_ptr that lost ownership and is now holding NULL, is no longer dereferenced. This behavior is quite counter-intuitive, since you would expect a copy constructor and assignment operator to look like this:
MyClass(MyClass const &other);
MyClass& operator=(MyClass const &rhs);
Instead, when we look at the std::auto_ptr as it comes with Microsoft Visual Studio .NET 2003, it looks like this:
auto_ptr(auto_ptr<_Ty>& _Right)
auto_ptr<_Ty>& operator=(auto_ptr<_Other>& _Right)
Spot the difference! That’s right, it violates general behavior, because the function parameters have no const modifier and are being changed in both functions! The fact that they have to be changed (the pointer they held is set to NULL to indicate they lost ownership), prevents the function arguments from being const. This can cause a lot of confusion!
Next: The concept of source and sink >>
More C# Articles
More By J. Nakamura