Clipping objects using queues

Developing on Ubuntu using Eclipse / gcc with -std = C ++ 0x.

I seem to have a problem with cropping objects that doesn't fit the other questions I've seen here. I have a very simple base class / child class inheritance model. The base class has one pure virtual function, which the child obviously implements:

class Parent{
public:
    Parent();
    virtual ~Parent();
    virtual void DoStuff() = 0;
};

class Child : public Parent{
public:
    Child();
    virtual ~Child();
    virtual void DoStuff(); //Child can have "grandchildren"
};

      

I want to have a queue where I can store these objects for processing by the worker thread. I know I have to store pointers, otherwise I would guarantee slicing. So, in the class ("Processor") that does this, I:

typedef queue<Parent*> MYQUEUE; //#include <queue>
static MYQUEUE myQueue;

//Call this after creating "Child c;" and passing in &c:
void Processor::Enqueue(Parent* p) 
{
    myQueue.push(p);
}

void* Process(void* args) //function that becomes the worker thread
{
    while(true)
    {
        if(!myQueue.empty())
        {
            Parent* p = myQueue.front();
            p->DoStuff();
            myQueue.pop();
         }
    }
    return 0;
}

      

What happens is that the program crashes saying "pure virtual method" as if inheritance / polymorphism is not working properly. I know inheritance is set up correctly, because as I check, I have confirmed that it works:

Child c;
Parent* p = &c;
p->DoStuff();

      

Any guidance is much appreciated!

+3


source to share


2 answers


If you pass an object to a worker thread, it cannot be created on the stack. By the time the worker thread calls it, the parent thread has most likely abandoned this function and destroyed the object. You need to dynamically allocate (possibly via new

) it to the parent thread and only free ( delete

) to the worker thread after you're done with it.



As another note, you need to block access to queues if the parent can complete the job's job while it is running.

+2


source


An error means that the object pointed to p

at the point of call is of type Parent

. How this came about depends on the code you didn't show.



0


source







All Articles