[cpp] for_each中delete函数的适配问题

Wu Yongwei adah at sh163.net
Sat Dec 9 18:01:20 CST 2006


lijie wrote:

> 2006/12/6, lijie <cpunion at gmail.com>:
> 
>> 在 06-12-6,苏亚<su1981ya at 163.com> 写道:
>> > 这倒不用,c++会自动特化参数的,直接传Delete就可以了
>> >
>> > for_each(m_cpfsPosition.begin(),m_cpfsPosition.end(), Delete );
>>
>> 这样可以吗?Delete在特化以前是个不完整的类型,不能够直接使用,我在g++ 
>> 4.1.1上测试也是不行的,加上参数特化以后就可以了。
>>
> 
> 或者是写成一个仿函数:
> class Test{
>    public:
>    ~Test(){cout << "Test::~Test()" << endl;}
> };
> 
> struct Delete_{
>    template <class T>
>    void operator()(T* ptr){
>        delete ptr;
>    }
> };
> 
> static Delete_ Delete;
> 
> int main(){
>    vector<Test*> vec;
>    vec.push_back(new Test);
>    for_each(vec.begin(), vec.end(), Delete);
>    return 0;
> }

这个差不多了。定义静态对象似乎没必要?我在代码里是这样写的:

/**
 * Functor to delete objects pointed by a container of pointers.
 *
 * A typical usage might be like:
 * @code
 * list<Object*> l;
 * ...
 * for_each(l.begin(), l.end(), delete_object());
 * @endcode
 */
struct delete_object
{
    template <typename _Pointer>
    void operator()(_Pointer __ptr) const
    {
        delete __ptr;
    }
};

我有点忘了当初为什么没有用 T* 了,可能是为了对各种编译器的兼容性更好吧。

吴咏炜


More information about the Cpp mailing list