Move Assignment Ownership

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

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

public:
    Buffer(int n) : data(nullptr), size(n) {
        data = new uint8_t[size];
    }

    // Incorrect: allows deep copy of exclusive resource
    Buffer& operator=(Buffer& other) {
        delete[] data;
        size = other.size;
        data = other.data;
        other.data = nullptr;
        other.size = 0;
        return *this;
    }

    ~Buffer() {
        delete[] data;
    }

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

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

int main() {
    int N, M;
    cin >> N;

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

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

    A = B;   // Incorrect: performs copy instead of move

    A.print();
    B.print();

    return 0;
}

Solving Approach

 

 

 


 

Upvote
Downvote
Loading...

Input

4 10 20 30 40 3 1 2 3

Expected Output

1 2 3 No data