Shared Pointer Ownership

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

class DataStore {
    vector<int> data;

public:
    DataStore(int n) : data(n) {
        cout << "Data created" << endl;
    }

    ~DataStore() {
        cout << "Data destroyed" << endl;
    }

    void readInput() {
        for (int& v : data) {
            cin >> v;
        }
    }

    void print() const {
        for (size_t i = 0; i < data.size(); i++) {
            cout << data[i];
            if (i + 1 < data.size()) cout << " ";
        }
        cout << endl;
    }
};

// shared_ptr passed by value → shared ownership
void printInFunction(shared_ptr<DataStore> store) {
    cout << "Printed in function" << endl;
    store->print();
}

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

    {
        shared_ptr<DataStore> store = make_shared<DataStore>(N);

        store->readInput();

        printInFunction(store);

        cout << "Printed in main" << endl;
        store->print();
    }

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

3 10 20 30

Expected Output

Data created Printed in function 10 20 30 Printed in main 10 20 30 Data destroyed