Reputation:
void f(const Fraction& a)
{ Fraction b = a;
Fraction* c = new Fraction(3, 4);
Fraction* d = &a;
Fraction* e = new Fraction(7, 8);
Fraction* f = c;
delete f;
}
Which values do I delete? I think I only delete c which is dynamically allocated and rest of the objects are destroyed automatically when the function ends.
How about e? It is also dynamically allocated but we don't have any delete operator for e. The e is not de-allocated?
Thanks,
Upvotes: 1
Views: 1340
Reputation: 53339
The key insight which you're probably missing here is that delete
does not have any relationship with a specific variable - it has a relationship with a specific object stored at a certain memory address. It's commonly stated as a rule that "any object allocated with new
must be deallocated with delete
." But note the use of the word object - not variable.
Consider:
Fraction* a = new Fraction(3,4);
Fraction* b = a;
delete b;
In this example we deleted b
, which points to the Fraction
object allocated on the first line. We also could have deleted a
, which pointed to the same Fraction
object. As long as we delete every object allocated with new
(regardless of which pointer variable we use to access the object), there is no memory leak. Also note that if we delete both a
and b
then we have an error (undefined behavior via a double-delete).
Upvotes: 5
Reputation: 55897
You should delete c
(or f
), but not both and you should delete e
. For each new
should be delete
.
Upvotes: 4
Reputation: 4463
new Fraction(3, 4);
e
or more strictly saying memory allocated with new Fraction(7, 8);
will not be deallocated leading to memory leak.Upvotes: 1