81. Non-Copyable UART Handle

#include <iostream>
#include <cstdint>
using namespace std;

class UARTHardware {
private:
    int baud;

public:
    UARTHardware(int b) : baud(b) {}

    // Explicitly forbid copying
    UARTHardware(const UARTHardware&) = delete;
    UARTHardware& operator=(const UARTHardware&) = delete;

    void sendByte(uint8_t value) const {
        cout << "TX: " << (int)value;
    }
};

int main() {
    int baudRate;
    cin >> baudRate;

    int temp;
    cin >> temp;
    uint8_t byteToSend = (uint8_t)temp;

    UARTHardware uart(baudRate);

    // Demonstration: uncommenting this line will cause a compile error
    // UARTHardware copy = uart;

    uart.sendByte(byteToSend);
    return 0;
}

Explanation & Logic Summary:

This problem demonstrates situations where objects represent unique hardware resources that must not be copied.

Examples:

  • UART peripherals
  • DMA channels
  • Timers
  • GPIO controllers
  • Interrupt controller handles

Copying would create multiple owners of the same hardware, causing:

  • Corrupted registers
  • Double initialization
  • Conflicting transmissions
  • Firmware crashes

Deleting the copy constructor and copy assignment operator ensures the compiler enforces uniqueness, preventing a dangerous class of firmware bugs.

Firmware Relevance & Real-World Context:

Embedded systems rely heavily on exclusive hardware ownership.

Making drivers non-copyable is a standard safety practice used in:

  • STM32 HAL
  • Zephyr RTOS
  • Embedded C++ frameworks
  • Linux kernel handle wrappers

This problem teaches the safe pattern required when representing hardware peripherals in C++.

 

 

 

 

Loading...

Input

9600 65

Expected Output

TX: 65