Repair generated worker callbacks

from Smart pointers
C++23 (GCC 13.3.0) advanced 10 min 4 issues to find

Review this generated worker for ownership, expiration, and lifetime behavior.

Queue work without keeping Worker alive, make the status callback a safe no-op after destruction, and expose the current Job only as a non-owning borrow.

C++
class Worker : public std::enable_shared_from_this<Worker> {
public:
    explicit Worker(TaskQueue& queue) : queue_(queue) {}

    void schedule() {
        auto keep_alive = shared_from_this();
        queue_.push([keep_alive] { keep_alive->run(); });
    }

    std::function<void()> status_callback() {
        auto weak = weak_from_this();
        return [weak] { weak.lock()->print_status(); };
    }

    std::shared_ptr<Job> current_job() {
        return std::shared_ptr<Job>(job_.get());
    }

    void run();
    void print_status() const;

private:
    TaskQueue& queue_;
    std::unique_ptr<Job> job_ = std::make_unique<Job>();
};

generated code is illustrative, not from any one model

Open in playground
Report an error