Is it considered good programming to do this?
class A {
A() { /* open file handles, allocate memory etc */ }
~A() { /* close file handles, deallocate memory etc */ }
};
void f() {
A *p;
p = new A;
// do stuff with *p
// end of scope, local variable p goes out of scope, ~A gets called
}
ie expecting that when p goes out of scope, ~A will be called to do my tidying up?
Or should every new be explicitly balanced with a delete?
When p goes out of scope, ~A does not get called. This is a memory leak. In this case, you actually need to call delete to destroy the instance of A pointed to by p.
Right. One of the reasons to use new is because the lifetime of the object created exists outside of all scopes. It doesn't get destroyed until you explicitly destroy it (with delete).
1 2 3 4 5 6 7 8 9 10
void f()
{
{
A obj;
} // A's (obj) destructor is called here, as you'd expect
{
A* ptr;
} // A*'s destructor gets called here (read: A*'s, NOT A's)
}
Notice that in the second situation, it's the pointer that is going out of scope, not the object. In that case the pointer's destructor that occurs, not the object's destructor. (But of course, a pointer's destructor does nothing)
Right, that explains a few things. I will remember this as 'type A* is not a class and doesn't have a destructor (or it has one that doesn't do anything)'.