I’m trying to implement a Polymorphic Queue.
Here is my trial:
QQueue <Request *> requests;
while(...)
{
QString line = QString::fromUtf8(client->readLine()).trimmed();
if(...)){
Request *request=new Request();
request->tcpMessage=line.toUtf8();
request->decodeFromTcpMessage(); //this initialize variables in request using tcpMessage
if(request->requestType==REQUEST_LOGIN){
LoginRequest loginRequest;
request=&loginRequest;
request->tcpMessage=line.toUtf8();
request->decodeFromTcpMessage();
requests.enqueue(request);
}
//Here pointers in "requests" do not point to objects I created above, and I noticed that their destructors are also called.
LoginRequest *loginRequest2=dynamic_cast<LoginRequest *>(requests.dequeue());
loginRequest2->decodeFromTcpMessage();
}
}
Unfortunately, I could not manage to make work Polymorphic Queue with this code because of the reason I mentioned in second comment.I guess, I need to use smart-pointers, but how?
I’m open to any improvement of my code or a new implementation of polymorphic queue.
Thanks.
There are 2 problems in your source:
Request *request=new Request();, which gets abandoned by the laterrequest=&loginRequest;assignment (and is no longer deletable)LoginRequest loginRequest;variable gets destructed when the execution leaves the {} block where the variable is defined, resulting in a dangling pointer inrequest
I would suggest to remove the
Request *request=new Request();line, and later in theif(...){block assign the concreteLoginRequestobject byYou can get rid of the queued objects by deleting them manually when they got poped out of the queue (after they are processed), or by using a container-safe smartpointer in the queue (boost::shared_ptr is fine, maybe QT has also one of them, std::auto_ptr IS NOT container-safe).
PITFALL Also make sure that the destructor of Request is virtual, since you cannot delete objects by a pointer to its base classe when there is no virtual destructor in the base class(c++ can call the base class destructor with the derived class instance in this case, leading in undefined behavior like memory leaks or crashes)