Search code examples
c++pointersshared-ptrsmart-pointers

C++: Modify a vector of share_ptr elements


In a C++ program, I declare a variable e in this way:

shared_ptr<c_t> e = shared_ptr<c_t> (new c_t);

Then, e is initialized.

Later in the program, I want to resize e, using this function:

e->change(4);

Where the class c_t and the function c_t::change are defined as:

class c_t {

    public:
    vector<shared_ptr<double>> m;

    void change(int n) {
        vector<shared_ptr<c_double>> mm;
        shared_ptr<double> m_buffer = make_shared<c_double>();
        for(int i = 0; i < n; i++) {
            m_buffer = 3.14 * i;
            mm.push_back(m_buffer);
        };
        m = mm;
    };
};

However, this approach does not work. When I use an iterator to read e, I get that the values of e are inf. Why? How should I change e?

Edit: To read, actually to scale, the values of e, the class c_t uses this function:

void scaling(double factor) {
    for (auto it = m.begin(); it != m.end(); ++it) {
        m *= factor;
    };
};

Solution

  • m_buffer = 3.14 * i;
    

    m_buffer is of type std::shared_ptr. Your assignement makes no sense. You probably wanted to write:

    *m_buffer = 3.14 * i;
    

    Also you want to declare m_buffer inside the for loop so the values in the vector will have different values based on i.

    for(int i = 0; i < n; i++)
    {
        std::shared_ptr<double> m_buffer = std::make_shared<double>();
        *m_buffer = 3.14 * i;
        mm.push_back(m_buffer);
    };
    

    Or a shorter version:

    for(int i = 0; i < n; i++)
    {
        mm.push_back(std::make_shared<double>(3.14 * i));
    };
    

    Live demo