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

Explanation & Logic Summary:

std::shared_ptr allows multiple owners to manage the same object.
In this program, both main() and printInFunction() hold ownership of the same DataStore.
The object remains alive until the last owner goes out of scope, ensuring safe access in multiple execution contexts.
The destructor runs exactly once when ownership ends.

Firmware Relevance & Real-World Context:

In embedded Linux and RTOS-based systems, data such as sensor samples, lookup tables, or configuration blocks may be produced once and consumed by multiple processing stages.
std::shared_ptr enables this shared access safely when lifetime cannot be statically determined, but must be used carefully due to runtime overhead and ownership complexity.

 

 

 

 

Loading...

Input

3 10 20 30

Expected Output

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