سؤال

I have a consumer-producer situation where I am constantly pushing data into a list, if it doesn't already exist there, and then every few seconds I package and send the data to a server.

At the moment I have a thread that delays for some number of seconds, wakes up, sets a flag so nothing is added to the list, does the packaging, deleting items processed from the list, and then allows the program to start adding to the list again.

This was fine for a prototype but now I need to make it work better in a more realistic situation.

So, I want to have the producer get the information, and when the size is large enough or enough time elapses pass the list to a thread to process.

I want to pass the reference to the list, and unique_ptr would be beneficial so once it is moved the producer thread can just create a new list and for all practical purposes be using the same list as before.

But when I tried to change my list from

typedef list<string> STRINGQUEUE;
STRINGQUEUE newMachineQueue;

to

std::unique_ptr<STRINGQUEUE> newMachineQueue;

Then I get errors that insert is not a member of std::unique_ptr.

I don't think I want to use newMachineQueue.get() and then do my operations as I believe I lose the benefits of unique_ptr then.

So, how can I use unique_ptr on a list and be able to call the methods in the list?

هل كانت مفيدة؟

المحلول

Just use it like you would use a pointer.

newMachineQueue->insert(...);

You might be interested in the documentation.

You also don't need to use a unique_ptr, but you can just move the list and reassign a new one to it.

void consumer(std::list<string> list) {
  // accept by value!
}

std::list<string> machineQueue;
// hand-off to consumer
consumer(std::move(machineQueue));
machineQueue = std::list<string>{}; // new list
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top