Deep Copy Assignment Buffer

#include <iostream>
#include <cstdint>
#include <algorithm> // for std::copy

using namespace std;

class SensorBuffer {
private:
    uint8_t* data;
    int size;

public:
    // 1. Constructor: Allocate buffer of specific size
    SensorBuffer(int s) : size(s) {
        data = new uint8_t[size];
    }

    // 2. Destructor: Free the allocated buffer
    ~SensorBuffer() {
        delete[] data;
    }

    // 3. Copy Assignment Operator: Perform a deep copy
    SensorBuffer& operator=(const SensorBuffer& other) {
        // Step 1: Detect self-assignment (e.g., A = A)
        if (this == &other) {
            return *this;
        }

        // Step 2: Release previously owned memory
        delete[] data;

        // Step 3: Allocate new buffer matching source size
        size = other.size;
        data = new uint8_t[size];

        // Step 4: Copy every byte from the source buffer
        for (int i = 0; i < size; i++) {
            data[i] = other.data[i];
        }

        // Return a reference to the current object
        return *this;
    }

    void set(int index, uint8_t value) {
        if (index >= 0 && index < size) {
            data[index] = value;
        }
    }

    void print() const {
        for (int i = 0; i < size; i++) {
            cout << (int)data[i];
            if (i != size - 1) cout << " ";
        }
        cout << endl; // Added for clean output
    }
};

int main() {
    int N1, N2;

    // Read first buffer
    if (!(cin >> N1)) return 0;
    SensorBuffer A(N1);
    for (int i = 0; i < N1; i++) {
        int temp;
        cin >> temp;
        A.set(i, (uint8_t)temp);
    }

    // Read second buffer
    if (!(cin >> N2)) return 0;
    SensorBuffer B(N2);
    for (int i = 0; i < N2; i++) {
        int temp;
        cin >> temp;
        B.set(i, (uint8_t)temp);
    }

    // Deep copy occurs here via operator=
    A = B; 

    // Print final contents of A
    A.print();

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

4 10 20 30 40 4 1 1 1 1

Expected Output

1 1 1 1