1. Executive summary
Safety-critical firmware implements functions whose failure can contribute to an unacceptable risk of harm. Its design must establish how the software behaves during normal operation and how it responds when inputs, resources or hardware no longer support that operation. In C++, this requires particular attention to object lifetime and to work performed implicitly by constructors, destructors and library facilities.
C++ provides useful ways to express these responsibilities. Value types can enforce admissible representations, ownership classes can control resource release, and interfaces can separate control decisions from hardware implementations. These mechanisms become dependable when their guarantees match the behaviour of the system. A buffer must remain available for as long as a peripheral or consumer uses it, and the execution time of cleanup must fit the path that performs it.
This paper examines how to make those relationships explicit in safety-critical embedded C++ firmware. It covers language and coding baselines, validated command types, controlled hardware activation, asynchronous buffer ownership and bounded resource use. It then connects exception handling, polymorphism and templates to the evidence required for release. The aim is to use C++ abstractions that make resource responsibilities easier to review and system behaviour easier to verify.
Publication details and citation
EEIO-INS-002 · Revision 1.2 · 2026
Published by EmbeddedExpertIO
Editor Israel Gbati
Suggested citation. EmbeddedExpertIO. Developing Safety-Critical Embedded C++ Firmware. EmbeddedExpertIO Engineering Insights, EEIO-INS-002, revision 1.2, 2026.
2. Language baseline and safety responsibilities
The language version, coding rules and software assurance framework serve different purposes, so a project needs to identify each explicitly. ISO/IEC 14882:2024 specifies the language commonly called C++23, whereas MISRA C++:2023 targets C++17. Its TC1:2026 corrections retain that language coverage [1, 2]. A compiler's support for a newer feature therefore does not bring that feature within the selected MISRA baseline.
The development policy should define the permitted language features and extensions, the libraries included in the build and the methods used to enforce the coding rules. It also needs to account for adopted software and justified deviations. These records give a reviewer a concrete basis for assessing a compliance claim, consistent with the principles of MISRA Compliance [3].
Software assurance extends beyond those coding decisions. ISO 26262-6:2018 addresses software development for automotive functional safety, and IEC 61508-3:2010 addresses software requirements within the IEC 61508 framework [4, 5]. For airborne software, FAA AC 20-115D recognises DO-178C and its supplements, including DO-332 for object-oriented technology, as an acceptable means of compliance [6]. The applicable framework determines the assurance activities and evidence required for the product.
An operation's suitability also depends on where it executes. Construction during controlled startup may permit work that would be unacceptable inside a deadline-critical callback. The design policy must connect each permitted operation to its callers and its resource and timing limits.
3. Command validity and type interfaces
Consider an actuator controller that accepts a duty command and acquires feedback through a peripheral. We will use this controller to examine command validation and the lifetime of the resources supporting it.
For a duty ratio expressed in thousandths, the admissible numerical range is zero to 1,000. Passing an unrestricted integer leaves every consumer responsible for remembering both the scale and the range. A value type can instead establish that representation when the command is created, as the C++17 example below shows.
#include <cstdint>
#include <optional>
class Duty final {
public:
[[nodiscard]] static std::optional<Duty>
from_per_mille(std::uint32_t raw) noexcept;
constexpr std::uint16_t per_mille() const noexcept {
return value_;
}
private:
explicit constexpr Duty(std::uint16_t value) noexcept
: value_{value} {}
std::uint16_t value_;
};
std::optional<Duty> Duty::from_per_mille(std::uint32_t raw) noexcept {
if (raw > 1000U)
return std::nullopt;
return Duty{static_cast<std::uint16_t>(raw)};
}
Because the factory checks the 32-bit input before narrowing it, an out-of-range value cannot become an apparently valid command through truncation. An empty result signals rejection, leaving zero available as a valid duty. The optional stores the contained value within its own storage, without a separate heap allocation for that value; the caller checks for presence before dereferencing it [7].
The type gives the control logic a precise starting point, but command acceptance also depends on the equipment's current state. An open interlock or an outdated feedback sample can make a numerically valid duty inappropriate. The controller must therefore evaluate those conditions when it accepts the command for use. Keeping numerical validity in the type and operating permission in the controller makes both responsibilities explicit.
4. Object lifetime and hardware activation
Before the controller can accept commands, its dependencies must be constructed in an order that preserves their lifetimes. A driver that borrows a bus needs the bus to exist throughout the driver's use of it. Declaring the bus member before the driver member establishes that order: C++ initialises non-static data members in declaration order and destroys them in reverse order, irrespective of the constructor's initialiser list [7].
Hardware activation introduces a further requirement. If a driver registers a callback during construction, an interrupt may reach the containing controller before the rest of its state is ready. In the arrangement shown in Figure 1, construction leaves the output inhibited. A separate activation operation validates the configuration and registers the callback only after the controller state it can observe is complete. It then enables interrupts and hardware operation, reporting any failure to the caller.
If activation fails part-way through, the controller retains responsibility for resources already acquired until they have been released or placed under the defined recovery procedure. Controlled shutdown follows the same ownership discipline. It first stops accepting new work, then drains or cancels outstanding operations and confirms that hardware and callbacks can no longer access objects scheduled for destruction.
Resource acquisition is initialisation, or RAII, supports this discipline by tying cleanup to an owner's lifetime. It applies to normal scope exit in code with or without exception handling [8]. The cost of that cleanup belongs to the execution path that destroys the object. Consequently, a destructor that flushes a stream, waits for a device or acquires a lock can make a return path substantially longer than its visible statements suggest.
Where stopping hardware can fail, an explicit shutdown operation gives the caller a status it can act on before destruction proceeds. The design must also provide a bounded response when quiescence cannot be confirmed, retaining any storage that remains accessible to the hardware. Reset and loss of power require their own system response because they can bypass normal C++ destruction.
An exclusive hardware owner must prevent copying from creating a second owner of the same resource. Moving also needs an explicit transfer policy: std::move makes an expression eligible for move-aware overload resolution, while the selected operation determines what happens to the resource. A defaulted move of a scalar hardware handle can copy its value and leave both objects appearing to own it. An owning class therefore needs a transfer operation that invalidates the source, or it must prohibit movement [7].
Startup timing also depends on where construction occurs. Dependencies between dynamically initialised objects in different translation units need explicit ordering, while a function-local static may require construction on first use and make concurrent callers wait for completion [7]. Completing that work before the time-critical phase removes it from the operational path. If first use can occur during operation, its construction and waiting time belong in the timing analysis.
5. Buffer ownership in asynchronous operations
With asynchronous transfers, the hardware's use of a buffer can outlast the task waiting for completion. Suppose the controller starts a direct memory access (DMA) transfer and the wait times out. If a local C++ owner then returns the buffer to a pool on scope exit, another caller can acquire storage that the peripheral is still writing. The destructor has followed the language rules, but the ownership design has released the buffer too early.
A persistent transfer manager resolves this mismatch by retaining responsibility for the buffer until the transfer and its users have finished. Figure 2 shows a normal sequence through Free, Reserved, InFlight, Ready and Processing, followed by return to Free. In this arrangement, the manager publishes a completed buffer only after the driver has released it. The consumer then holds it until processing is complete.
A timeout instead moves an in-flight transfer into Aborting. Before returning its slot to the pool, the manager must establish the documented stop or completion condition, driver release and the end of every application's access. If it cannot confirm those conditions, it quarantines the slot and invokes the specified fault response. Completion and cancellation can race, so their processing must agree on a single transition for the same transfer. A transaction identifier distinguishes successive uses of a slot and prevents a late notification from changing the state of a later transfer; that identifier must not be reused while an old notification carrying it can still arrive.
Zephyr's asynchronous UART interface provides a concrete example of how a driver distinguishes data availability from buffer release. UART_RX_RDY reports received data, whereas UART_RX_BUF_RELEASED reports that the driver no longer uses the buffer [9]. Application readers may still hold it after driver release. We therefore size the pool from the number of buffers that can remain in use across the complete processing path.
For example, one active DMA block, two completed blocks waiting for processing, one block held by a consumer and one spare require five distinct slots. With 256 payload bytes per slot, the payload allocation is 1,280 bytes, before descriptors, alignment and tracking state. The two waiting positions must be justified against arrival rate, service time and recovery delays. When the pool is exhausted, a defined drop policy can reject a newly offered block or discard one whose users have explicitly relinquished it. Storage still in use remains unavailable for reassignment.
Passing ownership between tasks also requires agreement with the queue interface. FreeRTOS queues copy item bytes, so placing a std::unique_ptr in such a queue does not invoke its C++ move constructor [10]. A trivially copyable slot index and transaction identifier can cross that interface, with the transfer manager enforcing the ownership protocol. Alternatively, a C++ queue can construct, move and destroy its elements. In either design, failed enqueue leaves a named owner responsible for the buffer, and the receiver rejects duplicate or stale identifiers [7].
A receiver also needs an ordered view of the data associated with the transferred slot. The publication mechanism must provide that ordering for the target's memory behaviour and execution contexts. An atomic operation may compile to a runtime helper rather than an inline instruction, so its execution time and potential to block must be assessed before use in an interrupt path [7, 11].
6. Memory allocation and execution cost
The buffer pool makes storage consumption explicit, but bounded storage is only part of the execution budget. A fixed number of elements can still invoke expensive constructors, copies or destructors. Table 1 distinguishes the storage properties of common C++ facilities from the operations that require further analysis [7].
Table 1. Storage properties and execution costs of selected C++ facilities.
| Facility | Storage property | Design requirement |
|---|---|---|
std::array<T, N> |
Holds a fixed number of elements. | Construction, copying and destruction of T. |
std::optional<T> |
Holds a value in its own storage, with an explicit empty state. | Operations performed by T; callers also check for presence. |
Reserved std::vector<T> |
Can insert without reallocating while the resulting size remains within capacity. | Capacity enforcement and all element operations. |
std::function |
Holds a callable behind a uniform interface; storage may be allocated dynamically. | Allocation and user-defined operations during construction, copying and invocation. |
For a reserved vector, an insertion that exceeds capacity can reallocate storage and invalidate references to its former elements. Staying within capacity avoids that reallocation, while the constructors and other element operations still run. Capacity planning must therefore address both the number of elements and the behaviour of the element type [7].
A supplied memory buffer also needs an explicit exhaustion policy. std::pmr::monotonic_buffer_resource obtains additional storage from its upstream resource when the current buffer cannot satisfy an allocation. Selecting null_memory_resource() as the upstream resource prevents that fallback from succeeding and makes the allocation throw std::bad_alloc [7]. For an operational path that excludes exceptions, the design must enforce capacity before that failure point can be reached.
Shared ownership introduces a different timing dependency. The context releasing the last std::shared_ptr owner runs the deleter, including any work reachable through it [7]. If several tasks can perform that final release, each is a possible location for cleanup. The timing analysis must account for the work in those contexts or the ownership design must arrange for release in a context with an adequate budget.
7. Fault propagation and response time
Resource exhaustion and hardware faults need a defined route from detection to the required system response. A checked status is often a direct way to represent an expected failure, provided each caller consumes it and takes the specified action. The interface should define the response associated with each failure status, and linked components must follow a consistent error-handling policy.
Declaring a function noexcept changes the consequence of an escaping exception: it causes std::terminate to be invoked. The function body can still call an operation that throws [7]. The implementation must therefore prevent that exception from escaping or deliberately provide for termination as part of the system's fault response. For GNU builds using -fno-exceptions, the component boundary needs particular attention because exception propagation through code built with that option is unsupported [12].
Where exceptions are retained, the response time includes the work between the throw site and entry to the handler. During stack unwinding, destructors run for completed automatic objects in the scopes being exited. When construction fails before the enclosing object is complete, completed base and member subobjects are destroyed; the enclosing object's destructor is not called. An exception escaping a destructor during unwinding invokes termination [7].
For a handled exception path, the response interval can be expressed as:
T_r = T_d + T_u + T_h + T_p.
Here, detection time is represented by T_d; propagation and cleanup by T_u; handler execution up to issue of the response command by T_h; and command delivery and physical response by T_p. Scheduling and communication delays belong to the interval in which they occur. Figure 3 shows why destructor work must be included before the handler can initiate the response.
Runtime storage is part of this assessment. GNU libstdc++ documents allocation for the exception object and associated runtime data, together with an emergency storage mechanism whose configuration affects its availability [12]. The relevant costs and failure behaviour must be assessed for the runtime included in the release.
Termination requires separate verification because complete unwinding is not guaranteed on that path. The system response must be traced through the termination behaviour to the required equipment state. For both handled faults and termination, the evidence must establish the physical response within its deadline, including any driver or transport delay between software action and actuator behaviour.
8. Polymorphism, templates and release verification
Alternative hardware implementations can share a C++ interface when they preserve the behaviour promised to callers. Virtual dispatch selects the implementation at runtime without inherently requiring heap allocation [7]. The design review must identify the permitted targets and their lifetimes, then check the meaning of each operation across them. If request_stop() submits a bus command, its completion contract must distinguish command submission from the actuator reaching the required state.
override allows the compiler to detect a function that was intended to override a base member but does not match it. The class interface should also make its destruction policy explicit. Where deletion through a base pointer is permitted, a virtual destructor provides the required derived-object destruction. A protected non-virtual destructor can instead prevent clients from deleting through that base interface [7, 8].
During construction and destruction, virtual calls resolve within the class currently being constructed or destroyed, rather than dispatching to a more-derived part [7]. Shutdown that requires derived-class behaviour must consequently occur while that part remains alive, before the destruction sequence in Figure 1.
Templates move the selection of concrete types and implementations to build time, but their costs still depend on the selected types. A ring buffer of integers and one containing owning objects can have the same bookkeeping and different cleanup behaviour. Release evidence therefore needs to identify the actual instantiations and the calls, stack use and storage they introduce. Likewise, a constexpr function can execute at runtime when called with runtime inputs [7]. Inspection of the released binary establishes whether assumptions about inlining, dispatch and helper calls hold for that build.
Compiler and library settings complete this implementation baseline. Runtime type information (RTTI) and exception configurations must be compatible across the linked image. GCC documents cases where mixing code built with and without RTTI fails, while its exception support imposes the propagation constraints described in Section 7 [12, 13]. The build record needs to preserve those settings with the compiler, libraries and device application binary interface (ABI).
Verification can then exercise the lifetime decisions that matter to the controller. The test cases should cover completion before timeout, completion racing with cancellation and completion after the waiting caller has returned. Failed activation, cancellation failure and pool exhaustion test whether ownership remains defined when normal progress stops. A delayed notification after attempted slot reuse tests whether the transaction protocol rejects stale activity. At each transition, the review must establish who controls the buffer's lifetime and which users can still access it.
Host instrumentation helps expose errors in those software paths. AddressSanitizer detects classes of memory misuse including use-after-free and use-after-scope. Clang's virtual-pointer check, -fsanitize=vptr, requires explicit selection, is outside the undefined group and is incompatible with -fno-rtti [14]. Coverage also needs interpretation: Clang distinguishes function coverage from instantiation coverage, so executing one template specialisation can leave another untested [15]. Evidence for the released specialisations makes that gap visible.
Target verification must establish how the released firmware meets requirements that depend on the peripheral, runtime or physical equipment. The release record should connect each selected implementation to verified ownership transitions, resource limits and fault-response timing, so that future changes can be assessed against the behaviour demonstrated on the target.
Training for engineering teams
EmbeddedExpertIO provides professional training in embedded systems and firmware development. If you are planning training for your team, we can help you choose courses that suit your engineers’ experience and the work ahead. Teams can enrol in a selected group of courses or arrange access to the full course library.
Discuss your team’s training requirements · support@embeddedexpert.io
9. References
[01] ISO. ISO/IEC 14882:2024, Programming languages, C++. Edition 7, October 2024. ISO catalogue. Standard C++ Foundation, The current C++ standard.
[02] MISRA. MISRA C++:2023, Guidelines for the use of C++17 in critical systems, including TC1:2026. Publication and technical corrigendum notice.
[03] MISRA. MISRA Compliance. Compliance principles.
[04] ISO. ISO 26262-6:2018, Road vehicles, Functional safety, Part 6: Product development at the software level. Edition 2, December 2018. ISO catalogue.
[05] IEC. IEC 61508-3:2010, Functional safety of electrical/electronic/programmable electronic safety-related systems, Part 3: Software requirements. Edition 2, April 2010. IEC catalogue.
[06] Federal Aviation Administration. AC 20-115D, Airborne Software Development Assurance Using EUROCAE ED-12( ) and RTCA DO-178( ). July 2017. Advisory circular.
[07] ISO/IEC JTC 1/SC 22/WG 21. N4659, Working Draft, Standard for Programming Language C++, March 2017. C++17 language and library provisions cited in this paper include object lifetime, initialisation, move operations, containers, smart pointers, memory resources, exception handling, virtual functions, templates and concurrency. Working draft.
[08] Stroustrup, B., and Sutter, H., editors. C++ Core Guidelines, particularly R.1, resource management through RAII, and C.35, base-class destructor policy. Guidelines.
[09] Zephyr Project. Asynchronous UART API, including received-data and buffer-release events. API documentation.
[10] FreeRTOS. FreeRTOS-Kernel, queue.c, particularly prvCopyDataToQueue and prvCopyDataFromQueue. Kernel implementation.
[11] GNU Compiler Collection. Built-in Functions for Memory Model Aware Atomic Operations. GCC manual.
[12] GNU Compiler Collection. libstdc++ manual, Exceptions. Runtime documentation.
[13] GNU Compiler Collection. Options Controlling C++ Dialect. GCC manual.
[14] LLVM Project. AddressSanitizer and UndefinedBehaviorSanitizer, including the separate virtual-pointer check.
[15] LLVM Project. Source-based Code Coverage, including function and instantiation coverage. Clang documentation.