Skip to the content.

< Previous: Getting Started | 🏠 Home | Next: Advanced Usage >


Basic Usage

Using cpp-pubsub is extremely straightforward. The central coordinator is the cpppubsub::PubSub broker, which manages all topics and subscriptions.

Publishing and Subscribing

Here is a simple example demonstrating how to create a broker, subscribe to a topic, publish a message, and receive it:

#include "cpppubsub.hpp"
#include <iostream>
#include <string>

int main() {
    // 1. Create the broker
    cpppubsub::PubSub broker;

    // 2. Subscribe to a topic (returns a shared_ptr to a Subscriber)
    auto sub = broker.Subscribe<std::string>("system_events");

    // 3. Publish a message to the topic
    broker.Publish("system_events", std::string("Initialization complete."));

    // 4. Receive messages non-blockingly
    while (auto msg = sub->try_receive()) {
        std::cout << "Received: " << *msg << std::endl;
    }

    return 0;
}

Queue Capacities & Overflow Policies

Memory Safety Built-In: The library correctly handles C++ smart pointers (like std::shared_ptr). When messages are discarded due to overflow policies or when a subscriber is destroyed, the library automatically cleans up the dropped data, fully respecting reference counts and preventing memory leaks.

By default, each subscriber has an internal queue capacity of 1000 messages. If the queue fills up because the subscriber is reading too slowly, the publisher will be blocked until space frees up to prevent memory exhaustion.

You can customize the maximum capacity and the overflow behavior when subscribing by providing a cpppubsub::OverflowPolicy.

// Allow up to 5000 messages, and drop the oldest message if the queue fills up
auto sub = broker.Subscribe<std::string>("fast_topic", 5000, cpppubsub::OverflowPolicy::DropOldest);

Available Policies


< Previous: Getting Started | 🏠 Home | Next: Advanced Usage >