Topics / C++ for Embedded / Q9
What are smart pointers and should you use them on an MCU?
Short answer: Smart pointers own the object they point to and release it automatically. std::unique_ptr has a single owner, is the same size as a raw pointer (with a stateless deleter) and has no run-time overhead, so it is fine on an MCU, especially with a custom deleter that returns memory to a pool. std::shared_ptr uses reference counting with a separately allocated control block and atomic increments, adding RAM, code and allocation, so it is usually avoided in firmware. Since most MCU code avoids the heap anyway, the main value is clear ownership.
#include <cstdio>
#include <memory>
struct Msg { int id; char data[32]; };
static Msg pool[4];
static bool used[4];
Msg *pool_alloc() { for (int i = 0; i < 4; i++) if (!used[i]) { used[i] = true; return &pool[i]; } return nullptr; }
struct PoolDeleter {
void operator()(Msg *m) const { used[m - pool] = false; std::printf("returned %d\n", m->id); }
};
using MsgPtr = std::unique_ptr<Msg, PoolDeleter>; // same size as Msg*
MsgPtr make_msg(int id)
{
Msg *m = pool_alloc();
if (m) m->id = id;
return MsgPtr(m); // may be empty if the pool is exhausted
}
int main()
{
auto a = make_msg(1);
{
auto b = make_msg(2);
} // "returned 2"
std::printf("sizeof(MsgPtr)=%zu\n", sizeof(MsgPtr));
} // "returned 1"
Guidance
- Prefer stack objects, static objects and references; use
unique_ptrwhen ownership must be passed around. - Avoid
shared_ptrin hard real-time paths (atomic operations, allocation, unpredictable destruction time when the last reference drops). std::make_uniqueallocates from the heap: only use it at initialisation if heap use is allowed.- Raw pointers are still fine for non-owning references;
std::spanand references make intent clearer. - Beware of destroying objects in ISRs through smart pointers (destructors may not be ISR-safe).