Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


smart pointer trouble


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 xinfinite33   Members   -  Reputation: 203

Like
0Likes
Like

Posted 24 December 2012 - 07:59 AM

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

 

 

 



Sponsor:

#2 Álvaro   Crossbones+   -  Reputation: 13662

Like
3Likes
Like

Posted 24 December 2012 - 09:54 AM

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




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS