Question

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
using namespace std;

struct delete_ptr
{
    template<typename T>
    void operator()(T*& t)
    {
        delete t;
        t = 0;
    }
};

struct is_null_ptr
{
    template<typename T>
    bool operator()(T*& t)
    {
        return t == 0;
    }
};

struct A
{
    static void removeDead(A*& a)
    {
        if(a and a->dead)
            delete_ptr()(a);
    }

    static void killSome(A* a)
    {
        if(a and a->isDead() == false and rand()%100 == 0)
        {
            static int counter = 0;
            cout << "Kill___" << ++counter << endl;
            a->kill();
        }
    }

    static void reviveSome(A* a)
    {

        if(a and a->isDead() and rand()%3 == 0)
        {
            static int counter = 0;
            cout << "Revive___" << ++counter << endl;
            a->revive();
        }
    }

    A():dead(false)
    {

    }

    virtual ~A()
    {
        static int counter = 0;
        cout << "Dtor___" << ++counter << endl;
    }

    bool isDead(){return dead;}
    void kill(){dead = true;}
    void revive(){dead = false;}

    bool dead;
};

int main()
{
    srand(time(0));
    vector<A*> as;
    for(int i = 0; i < 200; ++i)
    {
        A* a = new A;
        as.push_back(a);
    }


    for_each(as.begin(),as.end(),A::killSome);
    for_each(as.begin(),as.end(),A::reviveSome);

    for_each(as.begin(),as.end(),A::removeDead);
    as.erase( std::remove_if(as.begin(),as.end(),is_null_ptr()),as.end());
    cout << as.size() << endl;

    for_each(as.begin(),as.end(),delete_ptr());
    as.clear();

    return 0;
}

It allocates them, and prints the right output but I'm not sure this is the right thing I'm doing. I was just trying to use pointers in a vector and delete them when a certain condition happens, without using boost or c++11. So what do you think about it?

Was it helpful?

Solution

Since the only smart pointer present in the current STL (auto_ptr) cannot be used in containers, I would say your way is a good one under the given conditions.

You could think about implementing your own unique_ptr or shared_ptr however.

PS: There are many reasons to use pointers instead of the actual objects in a container, one is polymorphism. Another one is that the actual objects are already stored somewhere else (think of an index structure to already stored objects).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top