By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,341 Members | 1,376 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,341 IT Pros & Developers. It's quick & easy.

Check to see if object exists before attempting to delete it

P: 1
I have a composition object that is written in C++. The container class deletes the dynamic object in its destructor. However, if someone creates the object in the main and passes it to the container class, they will probably try to delete the dynamic object in their code. How do I test to see if the object exists before I delete it? The code below crashes since the dynamic Engine was deleted in the main. However, I need to clean up the memory in the class in case the Vehicle is created with the default constructor and the main() never uses the "new" keyword. Thanks!

int main( ){
// create composition object
Engine * engine = new Engine( );
Vehicle vehicle( engine );

// clean the memory
delete engine;
}

class Vehicle{
public:
// constructors
Vehicle( ){
engine = new Engine( );
}
Vehicle( Engine * engine ){
this->engine = engine;
}

// destructor
~Vehicle( ){
delete engine;
}
private:
Engine * engine;
};
Oct 10 '08 #1
Share this Question
Share on Google+
4 Replies


Ganon11
Expert 2.5K+
P: 3,652
No matter whether the default constructor is called or you use the 1 argument constructor, you are still assigning to an Engine* in Vehicle. Thus, you should be deleting engine only in Vehicle. Do not delete it in main() - when your Vehicle goes out of scope and the destructor is called, it will delete engine for you.
Oct 10 '08 #2

boxfish
Expert 100+
P: 469
How about setting engine = NULL wherever you delete it and then only deleting it if engine != NULL?
Oct 10 '08 #3

Banfa
Expert Mod 5K+
P: 8,916
How about setting engine = NULL wherever you delete it and then only deleting it if engine != NULL?
That wont work, setting the local variable in main to NULL will not effect the value of the engine member in Vehicle so the Vehicle destructor would still try to delete it and crash.

Ganon's idea is right, once you have passed ownership of the engine to the Vehicle it is up to the Vehicle to delete it.

Of course it might be better to just let Vehicle create its own engine all the time, then all the memory handling is nicely encapsulated by Vehicle. In the constructor that takes an engine * you would use that to initialise the engine created by Vehicle.

Another option would be to use handles rather than pointers.
Oct 10 '08 #4

weaknessforcats
Expert Mod 5K+
P: 9,197
Another option would be to use handles rather than pointers.
In fact, this is the solution.

Read this: http://bytes.com/forum/thread651599.html.
Oct 10 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.