Besides all the known benefits of using auto_ptrs, what are auto_ptr "worst-practices"?
Creating STL contrainers of auto_ptrs. auto_ptrs d开发者_C百科on'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:
- A const auto_ptr cannot have its ownership of the contained pointer transferred
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*
.
精彩评论