C++ Primer 4/e在Exception Handling这个地方有一个警告:‘The auto_ptr class template provides a measure of safety and convenience for handling dynamically allocated memory. To use auto_ptr correctly, we must adhere to the restrictions that the class imposes:
-
Do not use an auto_ptr to hold a pointer to a statically allocated object. Otherwise, when the auto_ptr itself is destroyed, it will attempt to delete a pointer to a nondynamically allocated object, resulting in undefined behavior.
-
Never use two auto_ptrs to refer to the same object. One obvious way to make this mistake is to use the same pointer to initialize or to reset two different auto_ptr objects. A more subtle way to make this mistake would be to use the result from get on one auto_ptr to initialize or reset another.
-
Do not use an auto_ptr to hold a pointer to a dynamically allocated array. When the auto_ptr is destroyed, it frees only a single objectit uses the plain delete operator, not the array delete [] operator.
-
Do not store an auto_ptr in a container. Containers require that the types they hold define copy and assignment to behave similarly to how those operations behave on the built-in types: After the copy (or assignment), the two objects must have the same value. auto_ptr does not meet this requirement.
’
中文版的这样写:‘auto_ptr class template 为“管理动态配置记忆体”提供了一个安全方便的方法。欲正确使用auto_ptr,我们必须遵守它所要求的条件:
- 不要使用auto_ptr保存“指向静态配置物”的指标。否则当这个auto_ptr被销毁,它会尝试删除一个非动态配置物,导致不明确结果。
- 绝对不要令两个auto_ptr指向同一个物件。明显犯此错误的一种方式是,以同一个指标初始化或reset()两个不同的auto_ptr物件。另一个犯此错误的隐微方式是,以“auto_ptr物件的get()的返回值”初始化或reset()另一个auto_ptr物件。
- 不要以auto_ptr物件保存动态配置的array。当这个auto_ptr物件被销毁,它只会释放一个物件。是的,它仅仅使用delete而不使用delete[]。
- 不要将auto_ptr物件保存于容器,因为容器要求其所保存的物件的型别的复制和赋值运算,必须与内建型别的对应运算行为一致:复制或赋值后左右两物件必须有相同的内容。但auto_ptr无法满足这一需求。
’
嗯,收录起来!