#include <vector>
#include <iostream>
using namespace std;
class A {
private :
int nId;
public:
A(int n) { nId = n;
cout << nId << " contructor" << endl; }
~A( ) //没有被调用
{cout << nId << " destructor" << endl; }
};
int main() {
vector<A*> vp;
vp.push_back(new A(1));
vp.push_back(new A(2));
vp.clear(); //不调用~A()
A a(4);
return 0;
}
上述程序的输出为:
1 constructor
2 constructor
4 constructor
4 destructor
4 constructor之前没有输出1 destructor和2 destructor,说明析构函数~A()没有被调用
vector.clear()做的唯一的事情就是调用vector.tcc中的erase函数:
template<typename _Tp, typename _Alloc>
typename vector<_Tp,_Alloc>::iterator
vector<_Tp,_Alloc>::
erase(iterator __first, iterator __last)
{
iterator __i(copy(__last, end(), __first));
std::_Destroy(__i, end());//关键!!
this->_M_impl._M_finish = this->_M_impl._M_finish - (__last - __first);
return __first;
}
erase会调用stl_construct.h中的_destroy函数,以下是源代码:
/**
* @if maint
* Destroy the object pointed to by a pointer type.
* @endif
*/
template<typename _Tp>
inline void
_Destroy(_Tp* __pointer)
{ __pointer->~_Tp(); }
/**
* @if maint
* Destroy a range of objects with nontrivial destructors.
*
* This is a helper function used only by _Destroy().
* @endif
*/
template<typename _ForwardIterator>
inline void
__destroy_aux(_ForwardIterator __first, _ForwardIterator __last,
__false_type)
{ for ( ; __first != __last; ++__first) std::_Destroy(&*__first); }
/**
* @if maint
* Destroy a range of objects with trivial destructors. Since the destructors
* are trivial, there's nothing to do and hopefully this function will be
* entirely optimized away.
*
* This is a helper function used only by _Destroy().
* @endif
*/
template<typename _ForwardIterator>
inline void
__destroy_aux(_ForwardIterator, _ForwardIterator, __true_type)
{ }
/**
* @if maint
* Destroy a range of objects. If the value_type of the object has
* a trivial destructor, the compiler should optimize all of this
* away, otherwise the objects' destructors must be invoked.
* @endif
*/
template<typename _ForwardIterator>
inline void
_Destroy(_ForwardIterator __first, _ForwardIterator __last)
{
typedef typename iterator_traits<_ForwardIterator>::value_type
_Value_type;
typedef typename __type_traits<_Value_type>::has_trivial_destructor
_Has_trivial_destructor;
std::__destroy_aux(__first, __last, _Has_trivial_destructor());
}
} // namespace std
但当vector中存储的是指向对象的指针时,调用的是第3,4个_destroy函数,其实什么也没干!
当然size之类的还是会被设为0的。。