Unique Pointer Custom Deleter

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

class DataBlock {
public:
    uint8_t* buf1;
    uint8_t* buf2;
    int size;

    // Constructor allocates memory
    DataBlock(int n) : size(n) {
        buf1 = new uint8_t[n];
        buf2 = new uint8_t[n];
    }

    // Destructor automatically frees memory when the object dies
    ~DataBlock() {
        delete[] buf1;
        delete[] buf2;
        cout << "Object cleaned" << endl;
    }

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

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

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

    {
        // Because we have a Destructor, we just use a normal unique_ptr!
        unique_ptr<DataBlock> block(new DataBlock(N));

        for (int i = 0; i < N; i++) {
            int temp;
            cin >> temp;
            block->set(i, (uint8_t)temp);
        }

        block->print();
        
    } // The unique_ptr destroys 'block', which triggers ~DataBlock()

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

1 0

Expected Output

0 Object cleaned