slowsword
slowsword

Reputation: 314

C++ queues of pointers to object c2228 error

I am trying to have a queue of objects and modify them for later. Since making a queue just makes a copy after modifying them in the queue and removing them, they disappear. So I need a queue of pointers to my objects to get around this (or so i understand).

My Class:

class process { 
    int waittime;
    queue<int> cpuburst, iotime;
   }

Then I create my queue like this:

process *P1;
process *P2;

P1 = new process(//info to fill my P1 with data);
P2 = new process(//info to fill my P2 with data);

queue<process *> readyque;
queue<process *> onCPU;

readyque.push(P1);
readyque.push(P2);

That compiles fine, but when i try to do anything to the queue with the .front() or .push() i get the error C2228: left of '.cpuburst' must have class/struct/union and i get the error IntelliSense: expression must have class type for the "onCPU"

on this line:

x = onCPU.front().cpuburst.front() + y;

I'm just trying to get x to be equal to what ever is in the top of the queue in my class, which is also on top of my onCPU queue

Upvotes: 0

Views: 588

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

Since onCPU contains pointers, when you do front() you'll get a pointer out of it. To access a member of an object through a pointer, use ->:

x = onCPU.front()->cpuburst.front() + y;

Since you are unsure whether having a queue of pointers is a good idea, ask yourself this: should the process objects be part of the queue which has sole ownership of them? Or should the queue simply refer to objects created elsewhere?

If you can avoid dynamically allocating objects, that's always a good thing. Perhaps a std::queue<std::reference_wrapper<process>> would be useful.

If you want to keep dynamically allocating them, consider a smart pointer (such as std::unique_ptr or std::shared_ptr).

If you stick with raw pointers to dynamically allocated objects, don't forget to delete them.

Upvotes: 3

Related Questions