Search code examples
c++shared-ptrstdvector

vector of shared_ptrs, returning it from a function and modifying it


Essentially, I want 2 of my classes to be sharing some data, which i want to have as a vector of shared_ptr objects.

I have cut down my code into the following simple compilable example.

I want object A, to be looking at the data that was initialized in object B. However when I try and do push_back() inside a method of A, it hasnt changed the size of the vector of shared_ptr objects in B. (At the line with the comment "This is the point of interest".)

What approach do I need to use to get this functionality, or am I on the wrong track. (c++ newbie here)

#include <memory>
#include <vector>
#include <iostream>
using std::cout;
using std::endl;
class DataClass {
    public:
        int i_;
};
class B {
    public:
        // constructor:
        B() : my_data_(std::vector<std::shared_ptr<DataClass> >()) {
            my_data_.push_back(std::shared_ptr<DataClass> (new DataClass));
            my_data_.push_back(std::shared_ptr<DataClass> (new DataClass));
            my_data_[0]->i_ = 1;
            my_data_[1]->i_ = 2;
            cout<<my_data_.size()<<endl;
        };

        // return the data
        std::vector< std::shared_ptr<DataClass> > get_my_data() {
            return my_data_;
        };

        // check the data:
        void CheckData() {
            cout<<my_data_.size()<<endl; // This is the point of interest
        };
        // member variable
        std::vector< std::shared_ptr<DataClass> > my_data_;
};
class A {

    public:
        void start() {
            // begin interaction with B class:
            B b;

            // get the vector of data pointers:
            a_has_data_ = b.get_my_data();

            // modify some of the data:
            a_has_data_.push_back(std::shared_ptr<DataClass> (new DataClass));
            a_has_data_[2]->i_ = 42;

            b.CheckData(); 
        };
    private:
    std::vector< std::shared_ptr<DataClass> > a_has_data_;

};
int main() {
    A a;
    a.start();
}

Solution

  • You are returning a copy of the vector. You need to return a reference to the data:

    // return the data
    std::vector< std::shared_ptr<DataClass> >& get_my_data()
    {
            return my_data_;
    };
    

    That was A is accessing b's vector, not a copy of it.