Jump to content

Ref to Self


SpiderPig
 Share

Go to solution Solved by Josh,

Recommended Posts

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.

Link to comment
Share on other sites

  • Solution

The base object class or derived from the shared_from_this class:

https://www.ultraengine.com/learn/Object_Self?lang=cpp

https://www.ultraengine.com/learn/Object_As?lang=cpp

I don’t think you need to store a weak pointer to itself

  • Thanks 1

My job is to make tools you love, with the features you want, and performance you can't live without.

Link to comment
Share on other sites

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.

 Share

×
×
  • Create New...