Medium
Command queue taking ownership of a document
What happens when this program is built and run?
main.cpp
#include <functional>
#include <iostream>
#include <memory>
#include <queue>
#include <string>
struct Document {
std::string text;
};
class CommandQueue {
public:
void enqueue(std::function<void()> cmd) { pending_.push(std::move(cmd)); }
void runAll() {
while (!pending_.empty()) {
pending_.front()();
pending_.pop();
}
}
private:
std::queue<std::function<void()>> pending_;
};
int main() {
CommandQueue queue;
auto doc = std::make_unique<Document>(Document{"draft"});
queue.enqueue([d = std::move(doc)] {
d->text += " (saved)";
std::cout << d->text << "\n";
});
queue.runAll();
}44 of 44 in Design Patterns