auto_ptr的使用误区

来源:互联网 发布:java排序方法有哪几种 编辑:程序博客网 时间:2024/06/10 02:49

1. auto_ptrs cannot share ownership.
An auto_ptr must not refer to an object that is owned by another auto_ptr (or other
object). Otherwise, if the first pointer deletes the object, the other pointer suddenly refers
to a destroyed object, and any further read or write access may result in disaster.
2. auto_ptrs are not provided for arrays.
An auto_ptr is not allowed to refer to arrays. This is because an auto_ptr calls
delete instead of delete [] for the object it owns. Note that there is no equivalent
class in the C++ standard library that has the auto_ptr semantics for arrays. Instead,
the library provides several container classes to handle collections of data (see Chapter
5).
3. auto_ptrs are not "universal smart pointers."
An auto_ptr is not designed to solve other problems for which smart pointers might be
useful. In particular, they are not pointers for reference counting. (Pointers for reference
counting ensure that an object gets deleted only if the last of several smart pointers that
refer to that object gets destroyed.)
4. auto_ptrs don't meet the requirements for container elements.
An auto_ptr does not meet one of the most fundamental requirements for elements of
standard containers. That is, after a copy or an assignment of an auto_ptr, source and
sink are not equivalent. In fact, when an auto_ptr is assigned or copied, the source
auto_ptr gets modified because it transfers its value rather than copying it. So you
should not use an auto_ptr as an element of a standard container. Fortunately, the
design of the language and library prevents this misuse from compiling in a standardconforming
environment.
最后的结论:using nonconstant auto_ptrs is no safer than using ordinary pointers.
所以使用auto_ptr时尽量使用const

原创粉丝点击