Home > Software design >  Pointing from a shared_ptr to a list yields memory error
Pointing from a shared_ptr to a list yields memory error

Time:08-05

I'm trying to have a list of shared_ptr's to int. When I try to point to one of the elements on the list, if I have a shared_ptr to the object that will point to the element it fails.

#include <iostream>
#include <list>
using namespace std;

class A
{
    public:
    A(){};
    shared_ptr<int> p;
};

int main()
{
    list<shared_ptr<int>> l;
    l.push_back(make_shared<int>(1));
    cout << "counts to shared pointer: " << l.back().use_count() << endl;

    /* This works */
    A a1;
    a1.p = l.back();
    cout << "counts: " << l.back().use_count() << endl;

    /* This does not work */
    shared_ptr<A> a2;
    a2->p = l.back();
    cout << "counts: " << l.back().use_count() << endl;
}

Output:

counts: 1
counts: 2
fish: Job 1, './l' terminated by signal SIGSEGV (Address boundary error)

CodePudding user response:

/* This does not work */
shared_ptr<A> a2;
a2->p = l.back();

and it's not supposed to work. a2 is a shared pointer that does not own anything. Yet, you try to dereference it with the -> operator. The A object you think a2 owns doesn't exist! You need to make one, e.g., like you did with your int using make_shared().

  • Related