Besides all the known benefits of using auto_ptrs, what are auto_ptr "worst-practices"?
Creating STL contrainers of auto_ptrs. auto_ptrs don't fulfill the 'CopyConstructable' requirement. See also Scott Meyer's "Effective STL", item 8.
Creating auto_ptrs of arrays Upon destruction, auto_ptr's destructor uses 'delete' (and never 'delete[]') to destroy the owned object, so this code yields undefined behavior: auto_ptr api(new int[42]);
Not taking care of copy-ctor and op= in a class using auto_ptr members. One might naively think that by using auto_ptr members one doesn't need to implement the copy constructor/assignment operator for a class. However, even a single auto_ptr member 'poisons' a class (i. e. violates the 'CopyConstructable' and 'Assignable' requirements). Objects of such classes would be partly damaged during the copy/assignment operation.
Are there even more auto_ptr pitfalls?
Not sure if this is a trap/pitfall, but it's certainly less than obvious:
In other words:
const auto_ptr<Foo> ap(new Foo());
auto_ptr<Foo> ap2;
ap2 = ap; // Not legal!
This is in fact quite useful if you want to take an auto_ptr argument and guarantee that you won't be taking ownership of the contained pointer, but it can also be surprising if you expect a const auto_ptr<Foo>
to behave like a Foo const*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With