Try Embedded

RAII and smart pointers

Tying resources to scope: lock guards, critical sections and uniqueptr.

Tie a resource to a scope

RAII ("resource acquisition is initialisation") means: acquire a resource in a constructor, release it in the destructor, and let the end of the scope do the releasing. Because C++ always runs a local object's destructor when the scope ends, through every return, break and early exit, the release can never be forgotten.

In firmware the resources are rarely memory. They are things like:

  • an interrupt mask (a critical section)
  • a mutex
  • a chip-select line held low for an SPI transaction
  • a peripheral clock or power domain switched on for a measurement

The bug RAII prevents

Here is the C version of a critical section with an early return. The second return forgets to re-enable interrupts:

int queue_pop(queue_t *q, uint8_t *out) {
  uint32_t primask = irq_save();
  if (q->count == 0) {
    return -1;                 // BUG: interrupts stay disabled forever
  }
  *out = q->buf[q->tail];
  q->tail = (q->tail + 1) % QUEUE_SIZE;
  q->count--;
  irq_restore(primask);
  return 0;
}

The C fix is discipline: a single exit point, or goto out. The C++ fix is a guard object:

class CriticalSection {
public:
  CriticalSection() : primask_(__get_PRIMASK()) { __disable_irq(); }
  ~CriticalSection() { __set_PRIMASK(primask_); }
  CriticalSection(const CriticalSection &) = delete;
  CriticalSection &operator=(const CriticalSection &) = delete;
private:
  uint32_t primask_;
};

int Queue::pop(uint8_t &out) {
  CriticalSection lock;          // interrupts off from here...
  if (count_ == 0) return -1;    // ...and back on here
  out = buf_[tail_];
  tail_ = (tail_ + 1) % size;
  --count_;
  return 0;                      // ...and here
}

Saving and restoring PRIMASK, rather than blindly re-enabling, makes the guard safe to nest: an inner guard restores the "disabled" state the outer one created.

The C program below shows the same discipline done by hand with a single exit, and counts how often the lock is taken and released:

#include <stdio.h>

static int depth;                       // stands in for the interrupt mask
static void lock(void)   { depth++; }
static void unlock(void) { depth--; }

static int buffer[4], count;

static int pop(int *out) {
  int result = -1;
  lock();
  if (count > 0) {
    *out = buffer[--count];
    result = 0;
  }
  unlock();                             // the only exit releases the lock
  return result;
}

int main(void) {
  int v;
  buffer[0] = 42; count = 1;
  printf("pop -> %d, lock depth %d\n", pop(&v), depth);
  printf("pop -> %d, lock depth %d\n", pop(&v), depth);
  return 0;
}

More guards worth writing

Chip select. Holds CS low for the lifetime of a transaction:

class SpiSelect {
public:
  explicit SpiSelect(Pin &cs) : cs_(cs) { cs_.low(); }
  ~SpiSelect() { cs_.high(); }
private:
  Pin &cs_;
};

{
  SpiSelect sel(flash_cs);
  spi.transfer(cmd);
  spi.transfer(addr);
}                                // CS released even if a check returns early

RTOS mutex. std::lock_guard works with any type that has lock() and unlock(), so a thin wrapper around a FreeRTOS mutex can use it directly. std::scoped_lock locks several mutexes without deadlock.

Smart pointers

std::unique_ptr owns one object and destroys it when it goes out of scope. It is the same size as a raw pointer and has no overhead. Even without a heap it is useful because of the custom deleter, which turns any "release" function into automatic clean-up:

struct PoolDeleter {
  void operator()(Packet *p) const { packet_pool.free(p); }
};
using PacketPtr = std::unique_ptr<Packet, PoolDeleter>;

PacketPtr p{packet_pool.alloc()};
if (!p) return Status::no_memory;
fill(*p);
radio.send(std::move(p));        // ownership passes to the radio driver

std::shared_ptr is different: it keeps a reference count in a separately allocated control block, and the count is updated atomically. It allocates and it costs on every copy, so most firmware avoids it. If shared ownership is really needed, an intrusive reference count inside a pool-allocated object is the usual substitute.

Pitfall: A guard only works if it has a name. CriticalSection(); on its own line creates a temporary that is destroyed immediately, so the protected code runs unprotected. Always write CriticalSection lock;.

Interview question: Explain RAII and give an embedded example that is not about memory.

Answer: RAII binds a resource's lifetime to an object's scope: the constructor acquires, the destructor releases, and C++ guarantees the destructor runs on every path out of the scope. Embedded examples: a critical-section guard that disables interrupts and restores the mask, an SPI chip-select guard that holds CS low for a transaction, a mutex lock guard, or a guard that powers a sensor's rail for a measurement. It removes the class of bugs where an early return skips the release.

Interview question: Is unique_ptr usable in firmware with no heap?

Answer: Yes. unique_ptr has no overhead over a raw pointer and does not require the heap: with a custom deleter it can return objects to a fixed-size pool, close a handle, or release a DMA buffer. It also documents and enforces single ownership, and std::move makes hand-offs explicit. shared_ptr is the one to avoid, because its control block allocates and its reference count is updated atomically on every copy.

Going deeper

Interview question: How would you make sure a camera gimbal's motors are never left driving after an error?

Answer: Tie the motor enable to an object's lifetime: a guard object enables the driver when it is created and disables it in its destructor, so every return path, early or not, turns the motor off. Back it with a watchdog and a hardware timeout on the driver itself, because RAII cannot help if the code hangs.

Interview question: What happens to a scope guard when an RTOS task is deleted while holding it?

Answer: Nothing: deleting a task does not unwind its stack or run destructors, so a held mutex or a disabled interrupt mask stays that way and other tasks may deadlock. RAII only works when scopes end normally. Design tasks to exit their loops and return (or signal for deletion) rather than being deleted from outside, and keep guards short.

Interview question: How can unique_ptr manage a buffer from a fixed-size pool?

Answer: Give it a custom deleter type whose operator() returns the pointer to the pool, for example std::unique_ptr<Packet, PoolDeleter>. Allocation returns the smart pointer; passing it with std::move transfers ownership, and when the last owner's scope ends the block automatically goes back to the pool, with no heap and no possibility of forgetting to free it.

Explain it: In your own words, explain why CriticalSection(); on its own line is a bug while CriticalSection lock; is correct.

Answer: CriticalSection(); creates a temporary object that is destroyed at the end of that same statement, so interrupts are disabled and immediately re-enabled before the code that needed protection runs. CriticalSection lock; creates a named object whose lifetime lasts until the end of the enclosing scope, so the protection covers every statement after it and ends automatically when the scope is left. RAII guards must always be named.