我正在尝试实现多态队列。这是我的试验:
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();
}
}
不幸的是,由于我在第二条评论中提到的原因,我无法使用此代码制作多态队列。我想,我需要使用智能指针,但是如何?我对代码的任何改进或多态队列的新实现持开放态度。
谢谢。