Apr 8, 2014 at 8:22am UTC
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 Apr 8, 2014 at 8:22am UTC
Apr 8, 2014 at 9:42am UTC
ok, so it is correct that it is destroyed 2 time ...
Why i have to introduce this modify?
Thanks in advance
Apr 8, 2014 at 10:02am UTC
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 Apr 8, 2014 at 10:04am UTC
Apr 8, 2014 at 1:14pm UTC
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 Apr 8, 2014 at 1:14pm UTC
Apr 8, 2014 at 2:15pm UTC
@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 :)