|
-
May 29th, 2013, 04:06 AM
#11
Re: Self-Deleting Objects with Inheritance
 Originally Posted by FrOzeN89
A very common example usage of my class would be a button that brings up the Settings form. i.e:
Code:
void btn_Settings(Object *sender, EventArgs *e)
{
FormSetup fs(L"Settings", 600, 400);
fs.Events.Create = fSettings_Create;
Form *fSettings = new Form(fs);
// After the next line Show() this function finishes and the shared_ptr goes out of scope which deletes my object.
// As soon as I move the mouse over the Settings window my program crashes because of an Access Violation when Windows tries calling Form::WndProc.
// std::shared_ptr<Form> fSettings(new Form(fs)); // Deletes Form too soon!
fSettings->Show();
};
Of course it will delete it too soon. This has nothing to do with shared_ptr, but with C++. You create a local variable, so what happens to local variables when a function returns?
You need to have a high-level design that properly implements your idea of how long of a lifetime each one of your objects will have. If you declare a local variable, then its lifetime is local to that scope. If you declare a class member, its lifetime is determined by the lifetime of the object, etc.
Regards,
Paul McKenzie
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|