1.auto_ptr 为什么不能作为STL容器元素类型?
auto_ptr的源码,operator =的代码实现:
operator=(auto_ptr& __a) throw()
{
reset(__a.release());
return *this;
}
由于开发者在设计auto_ptr时,并未引入计数机制,故不能让两个auto_ptr指向同一块内存,会出现A正在使用而B却将共有的对象析构等严重问题。
所以在copy constructor或operator=时,要release参数的指针。
而STL中的operator = :
obj &operator=(const obj &rhs)
{}
由于参数是const obj &rhs,则程序不允许在此函数中改变rhs的值。
因此,auto_ptr和STL容器算法有很大的冲突,所以auto_ptr不能作为元素放入STL容器内。