• Advertisement
Sign in to follow this  

smart pointer trouble

This topic is 1852 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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;
}

 

 

 

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement