SpiderPig Posted January 1, 2023 Share Posted January 1, 2023 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. Quote Link to comment Share on other sites More sharing options...
SpiderPig Posted January 1, 2023 Author Share Posted January 1, 2023 Using a weak_ptr instead did the trick. Quote Link to comment Share on other sites More sharing options...
Solution Josh Posted January 1, 2023 Solution Share Posted January 1, 2023 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 1 Quote 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 More sharing options...
Josh Posted January 1, 2023 Share Posted January 1, 2023 Also, never never never call Self or As in a constructor or destructor. 1 Quote 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 More sharing options...
Recommended Posts
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.