1

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?

pmr
  • 58,701
  • 10
  • 113
  • 156
James Black
  • 41,583
  • 10
  • 86
  • 166

1 Answers1

2

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
pmr
  • 58,701
  • 10
  • 113
  • 156
  • Oops, thank you. I used newMachineQueue.insert as I forgot that it isn't currently a pointer. – James Black Jan 30 '14 at 16:19
  • 1
    @JamesBlack I also added some code that does what you want without a `unique_ptr`. – pmr Jan 30 '14 at 16:22
  • Your edit solved another problem I was getting ready to ask about, as I got a weird error when trying to call the thread with the unique_ptr. Thanx – James Black Jan 30 '14 at 16:36
  • @JamesBlack I imagine you tried to copy a `unique_ptr` instead of moving it? No offense, you might want to try some basic C++11 before moving on. – pmr Jan 30 '14 at 17:33
  • I forgot that my variable wasn't a pointer, instead of new list() I just had list which created a problem, but when I used the unique_ptr I got some error in functional.hpp from VS2012, so your idea got around that. Later I may try to go back to unique_ptr. – James Black Jan 30 '14 at 18:37