我在运行我的程序时遇到了一些问题。它应该是一个非常简单的程序,可以模拟操作系统上的就绪队列。它使用优先级队列来存储进程对象(称为 PCB),并使用称为 CPU 的 PCB 指针来跟踪哪个进程在 CPU 中。该计划的要点是它应该在不销毁 PCB 的情况下回收 PCB。
我遇到的问题是,当我将 PCB 出队并将其分配给指针时,我收到此错误:
error: taking address of temporary [-fpermissive]
代码如下:
void OSSim::createProcess(){
PCB * newP;
if(unusedPCBs.isEmpty()) //unusedPCBs is a priorityQueue
newP = new PCB();
else{
newP = &(unusedPCBs.dequeue()); // THIS LINE IS CAUSING THE ERROR
}
newP->PID = pidCounter;
pidCounter++;
std::cout << "Process ID " << newP->PID << " created";
if(CPU == 0){
CPU = newP;
std::cout << " and moved to CPU\n";
} else {
readyQueue.enqueue(*newP);
std::cout << " and moved to the Ready Queue\n";
}
}
所以我搜索了 StackOverflow 并找到了一个解决方案,即创建一个临时的新 PCB(从被出列的 PCB)并将指针指向它:
void OSSim::createProcess(){
PCB * newP;
PCB temp;
if(unusedPCBs.isEmpty()) //unusedPCBs is a priorityQueue
newP = new PCB();
else{
temp = unusedPCBs.dequeue(); // THE "FIX"
newP = &temp;
}
newP->PID = pidCounter;
pidCounter++;
std::cout << "Process ID " << newP->PID << " created";
if(CPU == 0){
CPU = newP;
std::cout << " and moved to CPU\n";
} else {
readyQueue.enqueue(*newP);
std::cout << " and moved to the Ready Queue\n";
}
}
然而,问题是指针指向本地创建的 PCB 对象,因此一旦函数结束它就会消失。当我稍后尝试引用同一个 PCB 时,我发现它保存的数据已损坏。
所以我觉得自己陷入了第 22 条军规。我的目标是在 PCB 对象出队后重新使用它,而不销毁它并创建一个新对象。当我尝试用指针捕获它时出现“临时地址”错误,当我尝试通过临时创建一个新的 PCB 对象来存储它来捕获它时, 该对象在本地声明,并在例程结束后销毁。
如有任何建议,我们将不胜感激。非常感谢。
此外,这是我的 dequeue() 函数:
template <typename T>
T PriorityQueue<T>::dequeue(){
if(isEmpty()){
std::cout << "\n\nWARNING: Trying to dequeue empty queue\n\n";
throw 3;
} else {
Node * frontNode = head;
T result = frontNode -> data;
if(size == 1){
head = 0;
tail = 0;
} else {
head = frontNode -> prev;
head -> next = 0;
}
delete frontNode;
size--;
return result;
}
}
最佳答案
复制在堆上构造一个新的PCB。
if(unusedPCBs.isEmpty())
newP = new PCB();
else{
newP = new PCB( unusedPCBs.dequeue() );
}
关于c++ - 如何毫无问题地避免 "taking address of temporary"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564665/