Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 616
CptLightning Avatar asked Nov 21 '25 12:11

CptLightning


2 Answers

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.

like image 121
juanchopanza Avatar answered Nov 23 '25 01:11

juanchopanza


a_has_data_.push_back(std::shared_ptr<DataClass> (new DataClass));

With the return type is by copy, the above statement is going to modify the a_has_data_. And in b.CheckData(); you are actually checking the size of b's member.

Introduce a member function in A to check the vector size and you should see the increase.

like image 27
Mahesh Avatar answered Nov 23 '25 01:11

Mahesh