Topics / C++ for Embedded / Q4
What is RAII?
Short answer: Resource Acquisition Is Initialisation: a resource (lock, interrupt mask, peripheral clock, chip-select line, buffer) is acquired in an object's constructor and released in its destructor. Because destructors run automatically when the object goes out of scope — on every return path — the resource can never be leaked or left locked by an early return. It costs nothing at run time compared with doing it by hand.
#include <cstdint>
#include <cstdio>
// stand-ins for __get_PRIMASK / __disable_irq / __set_PRIMASK on Cortex-M
static uint32_t primask;
static uint32_t get_primask() { return primask; }
static void disable_irq() { primask = 1; }
static void set_primask(uint32_t v) { primask = v; }
class CriticalSection {
public:
CriticalSection() : saved_(get_primask()) { disable_irq(); }
~CriticalSection() { set_primask(saved_); } // restores the previous state (nesting-safe)
CriticalSection(const CriticalSection &) = delete; // non-copyable
CriticalSection &operator=(const CriticalSection &) = delete;
private:
uint32_t saved_;
};
static int shared_counter;
bool update(int v)
{
CriticalSection cs; // interrupts off from here...
if (v < 0) return false; // ...restored on this path
shared_counter += v;
return true; // ...and on this one
}
int main()
{
update(5); update(-1);
std::printf("counter=%d primask=%u\n", shared_counter, (unsigned)primask); // counter=5 primask=0
}
Other RAII uses in firmware
std::lock_guard/std::scoped_lockaround RTOS mutexes (wrap the RTOS API in a class withlock()/unlock()).ChipSelect cs(spi_dev);asserts CS for the duration of a transaction.- Peripheral power or clock enable for a scope; DMA buffer ownership; file handles.
std::unique_ptrwith a custom deleter (e.g. returning a buffer to a pool).
Rules: make RAII classes non-copyable (or movable only, transferring ownership), never throw from destructors, and keep the destructor's work short in interrupt-sensitive code.