Destructor called 2 time

Why in this code the destructor is called 2 time?
How can i avoid it?

Thanks in advance .


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
int _tmain(int argc, _TCHAR* argv[])
{

	

Elenco e1;
std::cout <<  "Test 2" <<std::endl;
std::cout<<e1.size()<<std::endl;
 

Persona p =new Persona("ab","bb");
e1.add(p);  // 1 call of destructor  the method is under   
 

 
  std::cout <<  "Test 3" << std::endl;
std::cout<<e1.size()<<std::endl;

	return 0;
}  //" call






void Elenco::add(Persona P){ 
	l.push_back(P); 
	 
}
1
2
3
4
void Elenco::add(Persona P){ 
	l.push_back(P); 
	 
}

P is passed by value. That means, new copy is made on the stack when add is called. When that copy is destroyed, ~Persona() is called to clean it up.

The second call to the destructor is made when e1 is being destroyed, the container within it is destroyed and that destroys each element.

The code should be:
1
2
3
4
void Elenco::add(const Persona& P){ 
	l.push_back(P); 
	 
}
Last edited on
ok, so it is correct that it is destroyed 2 time ...

Why i have to introduce this modify?

Thanks in advance
You don't have to introduce it. You can carry on passing by value, if you don't mind the extra copy being created. It's up to you.

The modification is so that the Persona object is passed into add as a reference, rather than creating a copy as it's passed by value.
Last edited on
Persona p =new Persona("ab","bb");

This doesn't look right. Shouldn't the new operator return a Persona*, not a Persona? Everywhere p is used, the code expects a Persona, but new would give you a Persona*.

If you are using new to allocate p, then you need a delete to avoid a memory leak, and that would give you another call to the destructor.
Last edited on
@MikeyBoy

Ok now it's clear :)
Thanks again :)


@doug4

Yes you are right, it is wrong ...
I'am at the beginning with c++.
it is only an attemptive.

Thanks :)

Topic archived. No new replies allowed.