Reputation: 10016
If I do something like:
void foo() {
bar* b2 = new bar();
b2 = new bar();
}
What happens to the first bar value initialized with new
? Is it overwritten by the second assignment, or should it be deleted using the delete keyword beforehand?
Upvotes: 1
Views: 1504
Reputation: 53871
This is a memory leak. C++ has allocated space for your object and then you lost all references to it, so it's going to sit there for the rest of your programs runtime being useless and space hungry.
That's why in C++ it's generally prefered not to use new
.
void foo() {
bar b2 = bar();
b2 = bar();
}
especially in situations where you only want to use the variable in 1 scope, allocating it on the stack is a much safer choice. Especially in the case of exceptions, the
Foo foo = new Foo();
...
delete foo;
is unsafe, what if ...
throws an exception? You leak! If you want safety and pointer semantics in C++11
unique_ptr<bar> b2;
if you really want pointer semantics. Now when all references to b2
are lost, it'll go delete itself. Note: Cycles still aren't broken and leak.
Upvotes: 5
Reputation: 13690
Your first line has three 'things' to do.
With this separation in mind it's obvious that you assign two times a value to one variable. Since you need this variable to delete the object your are lost after overwriting the first assigned value. This is one situation of a "memory leak".
Before you overwrite the variable b2
you should think about the first instance of the object of the class bar
. If it's not required anymore, use delete
to delete the object. If you still need it make a copy of the pointer.
Upvotes: 0
Reputation: 5101
Your first line:
bar* b2 = new bar()
will allocate sizeof(bar)
room on free store (and also call the constructor) and give you the address of this unit, say it's 0x123, this means that b2 remembers 0x123.
But now you overwrite your b2 - it now points to a new location given to you by new. This means that you no longer can reach the older memory unit you had been assigned by the first new call.
Upvotes: 0
Reputation: 3379
If you create something with new
you have to free it with delete, Otherwise memory leak will be there.
To prevent leak you should write:
void foo() {
bar* b2 = new bar();
delete b2;
b2 = new bar();
}
Upvotes: 0
Reputation: 129324
You should call delete
for the first b2
before assigning a new value to b2
. The second call will indeed overwrite the value in b2
(which is the address of the object created in the first new
).
In other words, your code has a memory leak, because the first bar
object is "lost".
Upvotes: 3