Effective STL 7 Delete the pointers before the container is destroyed

来源:互联网 发布:两个表格不同数据筛选 编辑:程序博客网 时间:2024/06/06 20:06
template<typename T>struct DeletObject:     public unary_function<const T*, void> {    void operator()(const T* ptr) const {        delete ptr;    }};class SpecialString:public string{...};deque<SpecialString*> dssp;...// undefined behavior! Deletion of a derived object via a base class // pointer where there is no virtual distructorfor_each(dssp.begin(), dssp.end(), DeletObject<String>()); 
struct DeleteObject {    template<typename T>        void operator()(const T* ptr) const {        delete ptr;    }};deque<SpecialString*> dssp;for_each(dssp.begin(), dssp.end(), DeletObject()); 

compilers know the type of pointer being passed to DeleteObject::operator(). so we have them automatically instantiate an operator() taking that type of pointer.

阅读全文
0 0
原创粉丝点击