class MyClass {
public:
string name;
MyClass() {
cout << "MyClass object created" << endl;
}
~MyClass() {
cout << "MyClass object deleted: " << name << endl;
}
};
void tester() {
MyClass *m1 = new MyClass();
m1->name = "m1";
MyClass m2;
m2.name = "m2";
}
int main() {
tester();
}
Destructor
Hi, another n00b c++ question. Look at the following code:
The output of this program is:
MyClass object created
MyClass object created
MyClass object deleted: m2
My question is why isn't the destructor called for the object pointed by m1?
Ooh, ooh, I know this one! The first object isn't deleted because you explicity allocated memory to it (new). Every new NEEDS a delete, otherwise you cause memory leaks.
Also, I think you should be able to call MyClass* m1 = new MyClass; because you're creating a new object, not a new function constructor pointer (...?).
Also, I think you should be able to call MyClass* m1 = new MyClass; because you're creating a new object, not a new function constructor pointer (...?).
You never deleted the memory for m1. When you allocate dynamic memory (using "new" or malloc()) you have to delete or free() the memory once you're finished using it.
In your program, you've allocated it, but never released it. It's actually caused a more serious problem called a memory leak. Because you never released the memory, it will still be used even after the program ends. With this program it won't cause any real problems, but say you were allocated 200mb of memory or more and never released it....
In your program, you've allocated it, but never released it. It's actually caused a more serious problem called a memory leak. Because you never released the memory, it will still be used even after the program ends. With this program it won't cause any real problems, but say you were allocated 200mb of memory or more and never released it....
Wow C++ is a nightmare! I just went back to the actual code I was working on and it has a recursive function that creates new objects. I fixed the memory leak, but for a more complicated program this would suck. Also, does this mean you can never have a nested calls like obj = (new Object)->createAnotherObject() since the intermediate object will never be deleted?
Yep, bare pointers to dynamic data can be a pain. That's why you should use automatic variables whenever possible. Use the common C++ idiom "RAII" (Resource Acquisition Is Initialization) which means using wrapper classes which handle the de/allocation cleanly in their constructor and destructor. For example, if you need to share some data among multiple objects, use a garbage-collected smart pointer (for example boost::smart_ptr)
No need to use new here, just make an automatic temporary:
Quote:
obj = (new Object)->createAnotherObject()
No need to use new here, just make an automatic temporary:
obj = Object().createAnotherObject();
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement