Deep Copy Assignment Buffer

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

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

public:

    SensorBuffer(int n): size(n){
        data = new uint8_t[size];
    }

    ~SensorBuffer(){
        delete[] data;
    }

    SensorBuffer& operator=(const SensorBuffer& other){ // deep copy as operator overload
        
        if(this = &other){  //handle self assignment
            return *this;
        }

        delete[] data;  //release previously allocated memory
        
        size = other.size;
        data = new uint8_t[size];
        for(int i=0; i<size; i++){
            data[i] = other.data[i];
        }
        return *this;
    }

    void set(int index, uint8_t value) {
        data[index] = value;
    }

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

int main() {
    int N1, N2;

    cin >> N1;
    SensorBuffer A(N1);
    for (int i = 0; i < N1; i++) {
        int temp;
        cin >> temp;
        A.set(i, (uint8_t)temp);
    }

    cin >> N2;
    SensorBuffer B(N2);
    for (int i = 0; i < N2; i++) {
        int temp;
        cin >> temp;
        B.set(i, (uint8_t)temp);
    }

    A = B;   // Deep copy must occur here

    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