Jump to content

Ref to Self


Go to solution Solved by Josh,

Recommended Posts

Posted

I have spent the last few hours bug hunting and have learnt that this is not a good idea -

class MyClass {
private:
	shared_ptr<MyClass> self = nullptr;
      
public:
	MyClass();
      ~MyClass();
      
};

shared_ptr<MyClass> CreateMyClass() {
	auto myclass = make_shared<MyClass>();
	myclass->self = myclass;

	return myclass;
}
      
//Program

auto myclass = CreateMyClass();
      
//Do Stuff
      
myclass = nullptr;//Go Away
//Nope, I still exist and havn't called my desctructer because your an idiot and
//have referened me inside me using a shared_ptr.  Maybe you should use enable_shared_from_this?

      

I have been using this method since forever and have never run into this problem.  The class in question had made a sprite but the sprite wasn't deleting when I set the class variable to nullptr.  Turns out this is why.  I can't remember why I gave up with enable_shared_from_this... at least a weak_ptr might work anyway.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...