Reputation: 47
class Foo{
public:
Foo(){
cout <<"C ";
}
~Foo(){
cout <<"D ";
}
};
void func(){
Foo* p = new Foo;
p = NULL;
}
int main(){
Foo a;
for (int i=0; i<1; i++){
Foo b;
if (true){
Foo c;
}
func();
}
return 0;
}
For this question, the output is C C C D C D D, and if I delete the func() in the main function, the output become C C C D D D, I understand the first 3 C where it come from, but I don't understand the remaining, please explain it, thanks.
Upvotes: 0
Views: 516
Reputation: 311088
The scope of the object a
is the scope of the outer code block of the function main. It is the first object that is created and the last object that is deleted.
int main(){
Foo a;
// ...
return 0;
}
C C C D C D D
| |
a a
Then in the for loop that has only one iteration there is created the object b
that is deleted after the first iteration of the loop
for (int i=0; i<1; i++){
Foo b;
// ...
}
C C C D C D D
| | | |
a b b a
Then in the block scope of the statement if
if (true){
Foo c;
}
there is created and deleted the object c
C C C D C D D
| | | | | |
a b c c b a
After that the function func
is called
func();
Inside the function there is created an unnamed object using the operator new and pointed to by the pointer p
.
void func(){
Foo* p = new Foo;
p = NULL;
}
C C C D C D D
| | | | | | |
a b c c p b a
This object is not deleted because the operator delete is not called for this object. So there is a memory leak.
That is all.
Upvotes: 3
Reputation: 4515
When the func();
call is included, the steps taken are:
Foo a; -> C
Foo b; -> C
Foo c; -> C
Left the scope of Foo c -> D
func(); call ->
new Foo; -> C
Finished func() call, left the scope of Foo b -> D
Left the scope of Foo a -> D
Note that the Foo object created in func() is never destructured, meaning you have a memory leak.
Upvotes: 0
Reputation: 12174
There order would be for C C C D C D D:
// memleak for p (in func)
Upvotes: 1
Reputation: 643
Upvotes: 2