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;
    }
};

// Passing by value increases the reference count, sharing ownership
void printInFunction(shared_ptr<DataStore> store) {
    cout << "Printed in function" << endl;
    store->print();
}

int main() {
    int N;
    if (!(cin >> N)) return 0;

    {
        // 1. Create DataStore using shared_ptr
        // std::make_shared is the efficient way to allocate the object and control block
        shared_ptr<DataStore> myStore = make_shared<DataStore>(N);

        // 2. Read input into DataStore
        myStore->readInput();

        // 3. Pass DataStore to printInFunction() by value
        printInFunction(myStore);

        // 4. Print data again here in main
        cout << "Printed in main" << endl;
        myStore->print();
        
        // The object stays alive here because myStore is still in scope
    } 
    // The object is destroyed here when myStore goes out of scope

    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