smart pointer trouble

Started by
0 comments, last by alvaro 11 years, 4 months ago

I've been trying to work with smart pointers pointers and i'm having trouble. if you have an object that has a pointer to another object, for example, my object stores a pointer to the closest object relative to itself, this makes a pointer cycle ,object 2 pointing to object 1 and object 1 pointing to object 2. how can i make it so that if an object gets deleted, all pointers pointing to it get set to NULL? iv'e tried this with shared pointers and auto pointers but i cant get anything to work how i want it. here's some code for a better understanding.


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

class person
{
    public:

        int value;
        shared_ptr<person> buddy;
        static int Count;

        person(int v)
        {
            this->value=v;
            Count++;
        }

        person(const person & other )
        {
            this->value=other.value;
            this->buddy=other.buddy;
        }

        ~person()
        {
            Count--;
        }



};

int person::Count=0;

int main()
{
        shared_ptr<person> test(new person(5));
        shared_ptr<person> test2(new person(37));
        test->buddy=test2;
        test2->buddy=test;
        cout<<(test->buddy)->value<<endl;
        cout<<(test2->buddy)->value<<endl;
        test=NULL;                             //destroy the first person and set all pointers pointing to it to NULL here. how do i do that?
        if(test2->buddy==NULL)
        {
            cout<<"null pointer detected. do nothing";
        }
        else
        {
            cout<<"person detected, print value: "<<test2->buddy->value;     //this shouldnt happen, it should detect null because test 1 was destroyed
        }

return 0;
}

Advertisement
Shared pointers encode shared ownership of the object being pointed to. You probably don't mean to say that your object owns its closest neighbor, and therefore you shouldn't use a shared_ptr for this. A weak_ptr is more likely what you need.

http://en.cppreference.com/w/cpp/memory/weak_ptr

This topic is closed to new replies.

Advertisement