Creating a standard queue of pointers in c++

c++, pointers, queue

Solution

If that's for lifetime management, then:

std::queue<std::shared_ptr<int>> CheckoutLine;
CheckoutLine.push(std::make_shared<int>(firstValeToBePushed))

If your queue is kind like a proxy, and someone else actually owns the lifetime of the objects, then definitely:

std::queue<std::reference_wrapper<int>> CheckoutLine;
CheckoutLine.push(firstValeToBePushed)

If you do not expose the queue anywhere and it's internal, then storing pointers is fine, as others suggested.

However, NEVER EVER expose to a client a collection of pointers, that's the worst thing one can do as you leave the burden of managing the lifetime on them, and that's the messier on collections.

Of course for primitive types or PODs, just copying is fine, no need to store pointers. Move semantics makes it easy even for non-PODs, unless you have some tricky construction or you object cannot implement move semantics.

`#include <functional>` for `std::reference_wrapper` and `#include <memory>` for `std::shared_ptr`, `std::unique_ptr` and friends. I'll assume you have access to a modern compiler.

Problem

Say I have a queue of integers, ``` #include <iostream> #include <queue> using namespace std; int main() { int firstValToBePushed = 1; queue<int> CheckoutLine; CheckoutLine.push(firstValeToBePushed); cout << CheckoutLine.front(); return 0; } ``` How can I do essentially the same thing using a queue which holds pointers to integers as opposed to integers like it currently does above. I plan on making a loop to make more than one value but this is just a more simple example. Thanks,

Original source