74. BufferTracker Destructor Logging

#include <iostream>
using namespace std;

class BufferTracker {
private:
    int count;

public:
    BufferTracker() : count(0) {}

    void addByte(int b) {
        count++;  // Count processed bytes
    }

    ~BufferTracker() {
        cout << "PROCESSED=" << count;
    }
};

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

    {
        BufferTracker tracker;

        for (int i = 0; i < n; i++) {
            int x;
            cin >> x;
            tracker.addByte(x);
        }
    } // Destructor prints output

    return 0;
}

Explanation & Logic Summary:

  • Constructor initializes the byte counter
  • addByte() increments the count for each processed byte
  • Destructor automatically reports total processed bytes
  • Demonstrates RAII-style end-of-transaction handling
  • No static variables or global state involved

Firmware Relevance & Real-World Context:

  • Embedded communication drivers often track processed bytes
  • DMA sessions, UART transactions, and SPI transfers log statistics on completion
  • Destructors act as safe auto-finalizers when scope exits
  • RAII ensures cleanup and reporting even during early returns or errors

 

 

 

 

Loading...

Input

5 1 2 3 4 5

Expected Output

PROCESSED=5